问题描述
我有一个非常简单的按钮绑定到命令
I have a very simple button binded to a command
<Button Content="Add" Margin="10,10,10,0" Command="{Binding SaveCommand}" ></Button>
我的命令代码
public ICommand SaveCommand
{
get;
internal set;
}
private bool CanExecuteSaveCommand()
{
return DateTime.Now.Second % 2 == 0;
}
private void CreateSaveCommand()
{
SaveCommand = new DelegateCommand(param => this.SaveExecute(), param => CanExecuteSaveCommand());
}
public void SaveExecute()
{
PharmacyItem newItem = new PharmacyItem();
newItem.Name = ItemToAdd.Name;
newItem.IsleNumber = ItemToAdd.IsleNumber;
newItem.ExpDate = ItemToAdd.ExpDate;
PI.Add(newItem);
}
代码基于CanExecuteSaveCommand有效地阻止了命令的运行,但是从未禁用该按钮,有没有办法实现此目的?
The code effectively blocks the command from running based on CanExecuteSaveCommand but the button is never disabled, is there a way to achieve this?
推荐答案
ICommand.CanExecute()
.通常,这通常取决于用户活动,例如键盘事件,焦点事件等.
ICommand.CanExecute()
is called automatically by WPF whenever it thinks the command availability may have changed. This generally tends to be on user activity, eg keyboard events, focus events etc.
由于您的命令可用性完全基于时间而变化,因此WPF无法猜测其已更改.相反,您需要通过调用CommandManager.InvalidateRequerySuggested();
Since your command availability changes purely based on time, WPF has no way of guessing that it has changed. Instead you need to give it a hint by calling CommandManager.InvalidateRequerySuggested();
由于命令可用性每秒钟更改一次,因此您需要设置一个计时器至少每秒钟调用一次此功能.
Since your command availability changes every second, you would need to set up a timer to call this function at least every second.
请注意,尽管InvalidateRequerySuggested()
是最简单的解决方案,但它将导致WPF重新评估所有命令的可用性.如果这是性能问题,则可以在ICommand
实例上引发CanExecuteChanged
事件.
Note that although InvalidateRequerySuggested()
is the easiest solution, it will cause WPF to re-evaluate ALL command availabilities. If this is a performance problem, you can raise the CanExecuteChanged
event on your ICommand
instance instead.
这篇关于ICommand不会使用CanExecute更新按钮上的IsEnabled的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!