C# 发出命令';s的执行取决于其他字段';s值
我正在开发一个小的WPF应用程序。本质上,用户浏览一个文件,然后单击“执行”在该文件上运行一些代码 在我的视图模型类中,我已将两次单击按钮(“浏览”和“执行”)绑定到C# 发出命令';s的执行取决于其他字段';s值,c#,wpf,mvvm,C#,Wpf,Mvvm,我正在开发一个小的WPF应用程序。本质上,用户浏览一个文件,然后单击“执行”在该文件上运行一些代码 在我的视图模型类中,我已将两次单击按钮(“浏览”和“执行”)绑定到ICommand internal class DelegateCommand : ICommand { private readonly Action _action; public DelegateCommand(Action action) { _action = action;
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
)联系起来,然后将按钮的状态(启用/禁用)链接到该状态。如果不向演示者添加IsFileSelected
observable属性,那么最好的方法是什么?通常我有一个ICommand
实例的基类,它为其Execute
和CanExecute
方法接受委托。在这种情况下,您可以通过闭包捕获范围内的内容。e、 g.大致如下:
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
}
}
OnCanExecuteChanged()应该是什么?xaml中的绑定是什么样子的?我发现xaml不需要更改,我可以通过添加RaisePropertyChangedEvent(“ExecuteCommand”)
@rookie查看Prism的它有一个包含OnCanExecuteChanged
用法的实现来触发对CanExecute
的重新评估,它只是基本的“引发事件”模式,用于引发作为ICommand一部分的事件。