我想用menuitem-click致电一个应用程序:
<MenuItem Header="{StaticResource MenuItemSave}" Command="ApplicationCommands.Save"/>
在我的ViewModel-constructor中,我将我的绑定限制为:
CommandBinding saveBinding = new CommandBinding(ApplicationCommands.Save, SaveCommand_Execute, SaveCommand_CanExecute);
CommandManager.RegisterClassCommandBinding(typeof(ViewModel_Main), saveBinding);
RegisterCommandBindings.Add(saveBinding);
现在我想处理命令,但根本不可执行。即使应该永远是真实的。
private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void SaveCommand_Execute(object sender, ExecutedRoutedEventArgs e)
{
//Stuff
}
我还尝试在我的初始化功能之后更新所有绑定:
CommandManager.InvalidateRequerySuggested();
但是我的菜单一直残疾。
谢谢!
我建议使用ICommand的此实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace Common
{
public class Command<TArgs> : ICommand
{
public Command(Action<TArgs> exDelegate)
{
_exDelegate = exDelegate;
}
public Command(Action<TArgs> exDelegate, Func<TArgs, bool> canDelegate)
{
_exDelegate = exDelegate;
_canDelegate = canDelegate;
}
protected Action<TArgs> _exDelegate;
protected Func<TArgs, bool> _canDelegate;
#region ICommand Members
public bool CanExecute(TArgs parameter)
{
if (_canDelegate == null)
return true;
return _canDelegate(parameter);
}
public void Execute(TArgs parameter)
{
if (_exDelegate != null)
{
_exDelegate(parameter);
}
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
bool ICommand.CanExecute(object parameter)
{
if (parameter != null)
{
var parameterType = parameter.GetType();
if (parameterType.FullName.Equals("MS.Internal.NamedObject"))
return false;
}
return CanExecute((TArgs)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((TArgs)parameter);
}
#endregion
}
}