c# - 使 Command 的 CanExecute 依赖于其他字段的值

标签 c# wpf mvvm

我正在开发一个小型 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 它的 ExecuteCanExecute 接受委托(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/

相关文章:

c# - 使用 System.Windows.Media.Animation 移动按钮动画

c# - 使用 StringFormat 在值中间添加单词

.net - 在wpf中使用复合集合获取选定项

asp.net - 我仍然犹豫是否使用 ViewModels 而不是 View 模型

c# - 在 C# 中使用 VB6 类

c# - .Net Core 在类里面使用 Session

c# - 将 ICommand 绑定(bind)到按钮?

c# - 如何在 C# 中使用 Caliburn.Micro 从 ListView 获取选定的项目和事件?

c# - 将 C# 代码组织到不同的文件中

wpf - 如何在文本框上实现自动保存?