雖然我發現這個問題的幾個答案,我不知道怎麼辦。所以請原諒我問。如何啓用/禁用按鈕?
我有一個WPF應用程序遵循MVVM模式。它包含在視圖模型綁定到的命令的按鈕:
<button Content="Login" Command="{Binding ProjectLoginCommand}"/>
的命令使用RelayCommand
。現在我想做以下事情:
- 用戶單擊按鈕並執行相應的命令。這工作。
- 在此命令中,另一個按鈕應被禁用,即不可點擊。
我發現這應該是可能的使用CanExecute
但誠實:我根本不明白它。鋤頭可以將按鈕設置爲啓用/禁用?
這是RelayCommand.cs
:
namespace MyApp.Helpers {
class RelayCommand : ICommand {
readonly Action<object> execute;
readonly Predicate<object> canExecute;
public RelayCommand(Action<object> execute) : this(execute, null) {
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null ? true : canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
execute(parameter);
}
}
}
這是我如何調用命令:
RelayCommand getProjectListCommand;
public ICommand GetProjectListCommand {
get {
if (getProjectListCommand == null) {
getProjectListCommand = new RelayCommand(param => this.ProjectLogin());
}
return getProjectListCommand;
}
}
你可以顯示兩個命令的'Execute'和'CanExecute'的代碼嗎? – Rachel
添加了命令用法。但實際上,除了'RelayCommand'類中的代碼之外,我沒有'Execute'或'CanExecute'的代碼。 –
謝謝羅伯特。按鈕的啓用/禁用自動綁定到'Command.CanExecute',因此您需要讓Button1在運行時將'CanButton2Execute'設置爲false,然後Button2將被禁用。 – Rachel