我有一个示例应用,其视图为:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApplication1.Commands"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ContextMenu x:Key="Menu">
<MenuItem Header="M" Command="{Binding MyCommand}" CommandParameter="{Binding}"/>
</ContextMenu>
</Window.Resources>
<DataGrid x:Name="maingrid" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="True" ContextMenu="{StaticResource Menu}"/>
我的cs代码是这样的:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
VM vm = new VM();
public MainWindow()
{
vm.Items = new BindingList<Entity>();
vm.MyCommand = new MyCommand();
InitializeComponent();
for (int i = 1; i < 1000; i++)
{
vm.Items.Add(new Entity() { X = i });
}
base.DataContext = vm;
Focus();
}
}
public class VM
{
public BindingList<Entity> Items { get; set; }
public Entity SelectedItem { get; set; }
public ICommand MyCommand { get; set; }
}
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
Debug.WriteLine("CanExecute Called!!!");
if (parameter != null && (parameter as VM).SelectedItem.X > 20)
{
return true;
}
else
{
return false;
}
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
throw new NotImplementedException();
}
}
public class Entity
{
public int X { get; set; }
public int X2 { get; set; }
public int X3 { get; set; }
public int X4 { get; set; }
public int X5 { get; set; }
public int X6 { get; set; }
}
}
现在,如果您启动应用程序并打开“输出”窗口并键入更改选定的行,则不会 “CanExecute Called !!!”输出。这是预期的行为,因为我希望只有当用户右键单击该行时才会触发命令。
现在右键单击一行,然后看“CanExecute Called !!!”出现在输出窗口中。
现在继续上下移动选择,你会不断看到“CanExecute Called !!!”消息来输出。
我希望命令仅在右键单击时触发。