問題:按鈕永遠不會啓用。按鈕保持禁用 - DelegateCommand不重新評估CanExecute處理程序
<Button Name="btnCompareAxises"Command="{Binding CompareCommand}"
Content="{Binding VM.CompareAxisButtonLabel}"
IsEnabled="{Binding VM.IsCompareButtonEnabled}">
</Button>
視圖模型構造:
this.CompareCommand = new DelegateCommand(CompareCommand, ValidateCompareCommand);
這個問題似乎涉及到按鈕的登記命令的CanExecute事件處理程序。 當應用程序加載時,CanExecute處理程序返回false。 這很好,因爲最初沒有滿足條件。
canExecute處理程序僅在應用程序啓動時或單擊按鈕時運行。您無法單擊禁用的按鈕,因此如果從CanExecute處理程序返回的初始值爲false,該按鈕將永遠保持禁用狀態!
問:
我必須再次啓用按鈕,只使用綁定到它的命令。 有點像,嘿命令請重新評估,如果這個按鈕的條件滿足?
爲什麼坐在部分強制下的IsEnabled屬性而不是在本地?
命令:
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? – stijn
不,我現在將其刪除,該按鈕將被自動禁用,不需要額外的綁定。謝謝 ! – Legends