【发布时间】:2012-11-21 17:00:44
【问题描述】:
虽然我已经找到了这个问题的几个答案,但我还是不明白。所以请原谅我问。
我有一个遵循 MVVM 模式的 WPF 应用程序。它包含一个绑定到视图模型中的命令的按钮:
<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这两个命令的代码吗? -
添加了命令用法。但实际上,我没有
Execute或CanExecute的代码,除了RelayCommand类中的代码。 -
谢谢罗伯特。 Button 的 Enabled/Disabled 自动绑定到
Command.CanExecute,因此您需要让 Button1 设置一些东西,使CanButton2Execute在运行时等于 false,然后 Button2 将被禁用。