【发布时间】:2016-12-20 06:19:02
【问题描述】:
问题:按钮永远无法启用。
<Button Name="btnCompareAxises"Command="{Binding CompareCommand}"
Content="{Binding VM.CompareAxisButtonLabel}"
IsEnabled="{Binding VM.IsCompareButtonEnabled}">
</Button>
ViewModel 构造函数:
this.CompareCommand = new DelegateCommand(CompareCommand, ValidateCompareCommand);
问题似乎与按钮的注册Command的CanExecute事件处理程序有关。 CanExecute 处理程序在应用程序加载时返回 false。 这很好,因为最初没有满足条件。
canExecute 处理程序仅在应用程序启动或单击按钮时运行。您不能单击禁用的按钮,因此如果从 CanExecute 处理程序返回的初始值为 false,则该按钮将永远保持禁用状态!
问题:
我是否必须再次启用该按钮,仅使用绑定到它的命令。
像,嘿命令,请重新评估此按钮的条件是否满足?
为什么 IsEnabled 属性位于 Coercion 部分而不是 local 部分?
命令:
public class DelegateCommand : ICommand
{
private readonly Func<object, bool> canExecute;
private readonly Action<object> execute;
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
public void RaiseCanExecuteChanged()
{
this.OnCanExecuteChanged();
}
protected virtual void OnCanExecuteChanged()
{
var handler = this.CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
【问题讨论】:
-
如果您已经绑定到通过 CanExecute 实现类似行为的命令,是否需要绑定 IsEnabled?
-
不,我现在去掉了,按钮会自动禁用,这里不需要额外绑定。谢谢!