[英]Make Command's CanExecute depend on other field's value
I'm working on a small WPF MVVM application. 我正在开发一个小型WPF MVVM应用程序。 In essence, the user browses for a file, then clicks "Execute" to run some code on the file.
实质上,用户浏览文件,然后单击“执行”以在文件上运行一些代码。
In my view model class, I've bound the two button clicks ("Browse" and "Execute") to an ICommand
. 在我的视图模型类中,我将两个按钮单击(“浏览”和“执行”)绑定到
ICommand
。
internal class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
internal class Presenter : INotifyPropertyChanged // VM class
{
private string filePath;
public string FilePath
{
get { return filePath; }
set
{
filePath = value;
RaisePropertyChangedEvent("FilePath");
}
}
public ICommand ExecuteCommand
{
// returns a DelegateCommand
}
public ICommand BrowseCommand
{
// how to enable/disable button based on whether or not a file has been selected?
}
}
Here, CanExecute
always returns true. 在这里,
CanExecute
总是返回true。 What I'd like to have happen, though, is for CanExecute
to be tied to whether or not a file has been selected (ie to whether or not FilePath.Length > 0
) and then link the button's status (enabled/disabled) to that. 但是,我想要发生的事情是,
CanExecute
与文件是否被选中(即是否为FilePath.Length > 0
)有关,然后将按钮的状态(启用/禁用)链接到那。 What's the best way to do this without adding an IsFileSelected
observable property to Presenter
? 如果不向
Presenter
添加IsFileSelected
可观察属性,最好的方法是什么?
Usually i have a base class for ICommand
instances that takes a delegate for both its Execute
and CanExecute
methods. 平时我有一个基类
ICommand
情况下,需要一个委托为它的Execute
和CanExecute
方法。 That being the case you can capture things in scope via closures. 在这种情况下,您可以通过闭包捕获范围内的事物。 eg something along those lines:
例如,沿着这些方向:
private readonly DelegateCommand _executeCommand;
public DelegateCommand ExecuteCommand { /* get only */ }
public Presenter()
{
_excuteCommand = new DelegateCommand
(
() => /* execute code here */,
() => FilePath != null /* this is can-execute */
);
}
public string FilePath
{
get { return filePath; }
set
{
filePath = value;
RaisePropertyChangedEvent("FilePath");
ExecuteCommand.OnCanExecuteChanged(); // So the bound control updates
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.