wpf Relay/ICommand vs DelegateCommand——差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16988250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:57:36  来源:igfitidea点击:

Relay/ICommand vs DelegateCommand -- Differences

c#wpf

提问by KeyboardFriendly

As far as I can tell the below code can be changed from Relay/ICommand Command to Delegate command and still bind the commands the same way! If I am wrong what are the differences and uses of each.

据我所知,下面的代码可以从 Relay/ICommand 命令更改为 Delegate 命令,并且仍然以相同的方式绑定命令!如果我错了,每个的区别和用途是什么。

private DelegateCommand something;
public DelegateCommand Something

Here is the full implementation

这是完整的实现

private RelayCommand something;
public ICommand Something
{
    get
    {
        if (something == null)
            something = new RelayCommand(SomethingMethod, CanSomething);
        return something;
    }
}

private bool CanSomething(object parameter)
{
    //just for readability return true
    return true;
}

private void SomethingMethod(object parameter)
{
    using (DatabaseContext context = new DatabaseContext())      
    {
        try { }
        catch(Exception ex)
        {
            throw new ApplicationException(string.Format("Something {0} to {1}", file, directory), ex);
        }
    }
}

回答by Reed Copsey

Neither DelegateCommandnor RelayCommandexist in the framework itself. They are provided by third party libraries.

既不存在DelegateCommand也不RelayCommand存在于框架本身。它们由第三方库提供。

Both are an implementation of ICommandwhich works by accepting a delegate and using that to provide the ICommandimplementation. As such, both classes have the same intent, and work in basically the same manner.

两者都是ICommand通过接受委托并使用它来提供ICommand实现来工作的实现。因此,两个类具有相同的意图,并且以基本相同的方式工作。

As for differences - there may be some subtle diffferences, depending on which framework you're using. For example, Prism's DelegateCommand<T>also has a concept of IActiveAware, which is used for building composite commands.

至于差异 - 可能会有一些细微的差异,具体取决于您使用的框架。比如 Prism'sDelegateCommand<T>也有一个 的概念IActiveAware,用于构建复合命令。