WPF自定义ICommand的实现和CanExecuteChanged事件 [英] WPF Custom ICommand implementation and the CanExecuteChanged event

查看:2225
本文介绍了WPF自定义ICommand的实现和CanExecuteChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WPF UI,我用我通过以下code指的是我的XAML RoutedCommands:

in my WPF UI, I use RoutedCommands that I refer to in my xaml via the following code:

Command="viewModel:MessageListViewModel.DeleteMessagesCommand"

我不喜欢这样的静态链接到我的ViewModel类,我觉得这不是像你一样创建一个自定义ICommand的实现和使用类似下面的语法

I don't like this static link to my ViewModel class,I think this is not as nice as creating a custom ICommand implementation and use a syntax like the following

Command="{Binding DeleteMessagesCommand}"

已经创建了一个,我发现我已经做了什么一个主要的缺点:RoutedCommands利用命令管理和(在某些方面是完全不透明的我)火CommandManager.RequerySuggested活动,使他们的CanExecute方法是自动重新查询。至于我的自定义实现,CanExecute只在启动时触发一次,并且永远不会再之后。

Having created one, I notice one major drawback of what I've done: RoutedCommands utilize the CommandManager and (in some way that is completely opaque to me) fire the CommandManager.RequerySuggested event, so that their CanExecute Method is requeried automatically. As for my custom implementation, CanExecute is only fired once at startup and never again after that.

没有任何人有一个优雅的解决这个?

Does anybody have an elegant solution for this?

推荐答案

就贯彻落实 CanExecuteChanged 事件如下:

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

在您指定的命令来控制,它订阅了 CanExecuteChanged 事件。如果重定向,它在 CommandManager.RequerySuggested 事件,每当触发 CommandManager.RequerySuggested 控制将被通报

When you assign the command to a control, it subscribes to the CanExecuteChanged event. If you "redirect" it to the CommandManager.RequerySuggested event, the control will be notified whenever CommandManager.RequerySuggested is triggered.

这篇关于WPF自定义ICommand的实现和CanExecuteChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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