Tôi đang gặp một số khó khăn với lệnh Trình đơn ngữ cảnh trên Kiểu xem của tôi.WPF ViewModel Lệnh CanExecute vấn đề
Tôi đang triển khai giao diện ICommand cho từng lệnh trong Mô hình xem, sau đó tạo ContextMenu trong tài nguyên của Chế độ xem (MainWindow) và sử dụng CommandReference từ MVVMToolkit để truy cập các lệnh DataContext (ViewModel) hiện tại. Khi tôi gỡ lỗi ứng dụng, có vẻ như phương thức CanExecute trên lệnh không được gọi ngoại trừ khi tạo cửa sổ, do đó các MenuItext Ngữ cảnh của tôi không được bật hoặc tắt như tôi mong đợi.
Tôi đã nấu một mẫu đơn giản (attached here), đây là biểu hiện của ứng dụng thực tế của tôi và được tóm tắt bên dưới. Mọi sự trợ giúp sẽ rất được trân trọng!
Đây là ViewModel
namespace WpfCommandTest
{
public class MainWindowViewModel
{
private List<string> data = new List<string>{ "One", "Two", "Three" };
// This is to simplify this example - normally we would link to
// Domain Model properties
public List<string> TestData
{
get { return data; }
set { data = value; }
}
// Bound Property for listview
public string SelectedItem { get; set; }
// Command to execute
public ICommand DisplayValue { get; private set; }
public MainWindowViewModel()
{
DisplayValue = new DisplayValueCommand(this);
}
}
}
Các DisplayValueCommand là ví dụ:
public class DisplayValueCommand : ICommand
{
private MainWindowViewModel viewModel;
public DisplayValueCommand(MainWindowViewModel viewModel)
{
this.viewModel = viewModel;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (viewModel.SelectedItem != null)
{
return viewModel.SelectedItem.Length == 3;
}
else return false;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show(viewModel.SelectedItem);
}
#endregion
}
Và cuối cùng, quan điểm được định nghĩa trong XAML:
<Window x:Class="WpfCommandTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCommandTest"
xmlns:mvvmtk="clr-namespace:MVVMToolkit"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<mvvmtk:CommandReference x:Key="showMessageCommandReference" Command="{Binding DisplayValue}" />
<ContextMenu x:Key="listContextMenu">
<MenuItem Header="Show MessageBox" Command="{StaticResource showMessageCommandReference}"/>
</ContextMenu>
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding TestData}" ContextMenu="{StaticResource listContextMenu}"
SelectedItem="{Binding SelectedItem}" />
</Grid>
</Window>
thứ tốt ... tôi đã tìm cách để làm điều này hôm nay! +1 – kevchadders