自定义命令更新CanExecute [英] Custom Command update CanExecute

查看:234
本文介绍了自定义命令更新CanExecute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在WPF应用程序中使用这个命令(我不喜欢它真的,但如果我必须 - >我必须):
http://wpftutorial.net/DelegateCommand.html

I have to use this Command in a WPF application (i dont like it really but if i have to -> i have to ): http://wpftutorial.net/DelegateCommand.html

但我在这里的主要问题是,我不想要在我的代码几乎每一行都调用

But the main problem I have here is that I don t want to have in nearly every line of my code a call to the


RaiseCanExecuteChanged()

RaiseCanExecuteChanged()

方法。所以我可以做那个自动像RoutedUICommand做的。

method. So what could I do to do that auto like RoutedUICommand does.

我有很多数据绑定和示例如果Foo.FooProp!= null命令可以执行。但我想尽可能少的代码,所以我必须注册事件无处不在或更新命令在我的应用程序....

I have a lot of databindings and as example if Foo.FooProp != null Command can execute. But I want as less code as possible and so I would have to register events everywhere or update commands all over my application....

推荐答案

您可以实现 DelegateCommand 的形式,它会在每次有可能的更改时调用添加到 CanExecuteChanged 结果在UI中。此示例使用 CommandManager。 RequerySuggested

You could implement a form of DelegateCommand which invokes the delegates added to CanExecuteChanged everytime there is a change of possible consequence in the UI. This example uses CommandManager.RequerySuggested.

public class AutoDelegateCommand : DelegateCommand, ICommand
{
    public AutoDelegateCommand(Action<object> execute)
        : base(execute)
    {
    }        

    public AutoDelegateCommand(Action<object> execute, Predicate<object> canExecute)
        : base(execute, canExecute)
    {
    }

    event EventHandler ICommand.CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}



我想我已经看过这样的例子之前,也许在MVVMLight工具包?

I think I've seen an example like this before, perhaps in the MVVMLight toolkit?

这篇关于自定义命令更新CanExecute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆