我正在开发一个小型 WPF MVVM应用。本质上,用户浏览文件,然后单击“执行”以在文件上运行一些代码。
在我的 View 模型类中,我将两次按钮点击(“浏览”和“执行”)绑定(bind)到一个 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?
}
}
此处,CanExecute
始终返回 true。不过,我希望发生的事情是将 CanExecute
与文件是否已被选中相关联(即是否 FilePath.Length > 0
) 然后将按钮的状态(启用/禁用)链接到它。在不向 Presenter
添加 IsFileSelected
可观察属性的情况下执行此操作的最佳方法是什么?
最佳答案
通常我有一个 ICommand
实例的基类,它为 both 它的 Execute
和 CanExecute
接受委托(delegate)方法。在这种情况下,您可以通过闭包捕获范围内的事物。例如沿着这些方向的东西:
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
}
}
关于c# - 使 Command 的 CanExecute 依赖于其他字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322176/