继续我对静态变量和XAML的挣扎,我无法解决使命令绑定变灰的问题。
View Model中的代码:
public static ICommand CancelCalender => _cancelCalender
?? (_cancelCalender = new CommandHandler(CancelCalender_Button, _canExecute));
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
参考,
xmlns:viewModels="clr-namespace:StaffShiftManager.ViewModels"
这些是我尝试绑定命令变量的方法:
Command="{x:Static viewModels:ViewModelBase.CancelCalender}"
和
Command="viewModels:ViewModelBase.CancelCalender"
和
Command="{Binding Source={x:Static viewModels:ViewModelBase.CancelCalender}}"
我有什么遗失的东西吗?任何帮助将不胜感激。
答案 0 :(得分:2)
基本上在ICommand CanExecute()
方法中,这将返回命令是否已启用\可以执行。
从false
返回CanExecute()
将禁用(灰显)按钮。
现在我稍微修改了您的代码以提供Func<bool>
作为CanExecute()
处理程序。这里会发生的是每次重新查询命令执行时它将执行您的canExecute
方法。
public class CommandHandler : ICommand
{
public CommandHandler(Action execute)
:this(execute, null)
{
}
public CommandHandler(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
_executeHandler = execute;
_canExecuteHandler = canExecute ?? (() => true);
}
Func<bool> _canExecuteHandler = () => true;
Action _executeHandler;
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecuteHandler();
}
public void Execute(object parameter)
{
_executeHandler?.Invoke();
}
}
canExecute
方法的默认实现不是返回true
。即使将null Func
传递给构造函数仍然会生成true。
只是添加一个我最喜欢的命令绑定器(比上面更高级)使用DelegateCommand
。我不记得我找到原始来源的地方(因为我没有写它)但更先进。