wpf - 如何简化 WPF/MVVM 的 ViewModels 中命令的实现?

标签 wpf mvvm delegatecommand

我注意到,在 MVVM-WPF 场景的 ViewModel 上实现命令时,我重复了很多代码。如下所示,标准实现包括类型为 ICommand 的公共(public)只读字段、私有(private) DelegateCommand 字段和用于执行逻辑的方法。 DelegateCommandICommand 的 get-accessor 中初始化。

考虑到每个命令的重复,如何才能压缩这种方法?

private DelegateCommand saveCommand;
private DelegateCommand commandClearInputFileList;
private DelegateCommand commandInputFilesDeleteSelected;

public ICommand SaveCommand {
    get {
        if (saveCommand == null) {
            saveCommand = new DelegateCommand(CommitDataBasePush);
        }
        return saveCommand;
    }
}

public ICommand CommandClearInputFileList {
    get {
        if (commandClearInputFileList == null) {
            commandClearInputFileList = new DelegateCommand(InputFilesClear);
        }
        return commandClearInputFileList;
    }
}

public ICommand CommandInputFilesDeleteSelected {
    get {
        if (commandInputFilesDeleteSelected == null) {
            commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
        }
        return commandInputFilesDeleteSelected;
    }
}

最佳答案

除了空合并运算符,您还可以使用 Lazy Loading :

private Lazy<DelegateCommand> _cmd = new Lazy<DelegateCommand>(() => new DelegateCommand(InputFilesClear) );

public ICommand CommandClearInputFileList { get { return _cmd.Value; } }

就个人而言,我已经放弃了命令,转而使用 Caliburn.Micro 提供的约定。框架。上面的命令将简单地替换为公共(public)方法。

关于wpf - 如何简化 WPF/MVVM 的 ViewModels 中命令的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615207/

相关文章:

c# - 如何在项目中找到 ViewModel?

c# - 由于 Window.EfectiveValues 保留导致内存泄漏

c# - 动态 WPF MVVM 数据网格行为

c# - C#WPF MVVM DataGrid MouseBinding仅适用于行

c# - Prism ( View 模型): Ensure a command does not get executed multiple times simultaneously

wpf - 使用 DelegateCommand 的 CanExecute 操作

c# - WPF CommandParameter 绑定(bind)和 canExecute

c# - 样式数据网格表 - 左上角

c# - WPF DPI 问题

Android bindingadapter不更新值