用MVVM模式做的项目,用ICommand命令绑定事件,代码如下:
ViewModel 里定义命令:public ICommand RemoveCommand { get; private set; },构造里初始化命令:RemoveCommand=new RelayCommand(Remove,CanExecute);
以下是RelayCommand 的定义。
public class RelayCommand : ICommand
{
#region Fields&Constructors
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region Icommand Members
public void Execute(object parameter)
{
//if (parameter==null)
//{
// return;
//}
if (!CanExecute(parameter))
{
throw new InvalidOperationException("The command is not valid for execution, check the CanExecute method before attempting to execute.");
}
_execute(parameter);
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
View里是右键菜单绑定的命令:
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="删除" Command="{Binding RemoveCommand}" InputGestureText="Delete"/>
</ContextMenu>
</DataGrid.ContextMenu>
以上代码在Win7旗舰版系统,XP系统以及Win8系统都运行正常,唯独Win7专业版运行不执行删除函数,在CanExecute那就返回False了,右键菜单变灰,但是Win7专业版安装了VS后就好了,但是不能每个用户使用软件时都要安装VS啊,感觉是一些组件不全或是组件比较低级,不知道原因。
后来的解决办法,就是在View.cs 里用 public static RoutedUICommand RemoveCommand = new RoutedUICommand();定义了命令
private void CommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
//判读条件是否执行删除命令
}
private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
//执行删除命令
}
在View里:首先添加这个:
<UserControl.CommandBindings>
<CommandBinding Command="view:AnimationEditor.RemoveCommand" CanExecute="CommandBinding_OnCanExecute" Executed="CommandBinding_OnExecuted" ></CommandBinding>
</UserControl.CommandBindings>
然后在右键菜单里:
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="删除" Command="view:Editor.RemoveCommand" InputGestureText="Delete"/>
</ContextMenu>
</DataGrid.ContextMenu>
如此修改在任何系统下都没问题了,可是我还是不知道具体原因,请高手指教。