如何附加命令来检查和取消选中CheckBox? [英] How do I attach commands to the checking and unchecking of a CheckBox?

查看:172
本文介绍了如何附加命令来检查和取消选中CheckBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ViewModel中,我有两个命令:

In my ViewModel I have two commands:

ICommand ExecuteMeOnCheck { get; }
ICommand ExecuteMeOnUncheck { get; }

我希望将这些命令附加到一个CheckBox,并且其中一个在执行检查时执行,另一个在未被选中的情况下执行。

I wish to attach these commands to a CheckBox and have one of them execute when it is checked and the other execute when it is unchecked. What's the best way to achieve this without cluttering the View with code-behind?

推荐答案

我发现这样做最简单的方法是实现此目的的最佳方法涉及借用一堆代码。我也认为你不想公开两个事件来改变状态。使您的命令CheckedChangedCommand而不是检查和未选中。将CheckBox.IsChecked依赖属性绑定到ViewModelClass上的属性。这样当你的命令被执行时,你只需要检查你的ViewModel中的值。

The simplest way I have found to do this involves borrowing a bunch of code. I also think that you do not want to expose two events for the state change. Make your command CheckedChangedCommand instead of Checked and Unchecked. Bind the CheckBox.IsChecked dependency property to a property on your ViewModelClass. That way when your command gets executed, you just check that value in your ViewModel.

首先,从,rel =nofollow noreferrer>WPF ViewModel工具包。您的帖子不清楚您是否有。

First, start using DelegateCommand from the WPF ViewModel toolkit. It isn't clear from your post whether you are or not.

接下来,下载。zip archive 从此链接的下载选项卡。

Next, download the .zip archive from the Downloads tab at this link.

存档有一个名为EventBehaviourFactory的类, DependencyProperty更容易。回到上面链接的主页选项卡,Samuel告诉你如何将XAML中的Command连接到ViewModel。这里是:

The archive has a class called EventBehaviourFactory that makes setting the DependencyProperty easier. Back on the Home tab at the above link, Samuel tells you how to wire up the Command in your XAML to the ViewModel. Here it is:

<TextBox ff:TextBoxBehaviour.TextChangedCommand="{Binding TextChanged}"/>

我使用了三个类(DelegateCommand,EventBehaviourFactory和TextBoxBehaviour)行,并使TextChanged事件工作在我的项目中约五分钟。

I used the three classes (DelegateCommand, EventBehaviourFactory and TextBoxBehaviour) line for line and had the TextChanged event working in my project in about five minutes.

将其扩展到其他控件(如您需要做的)的模式也很简单。我设法以同样的方式连线ListBox.SelectionChanged。创建一个新的ControlBehaviour类,并将Control替换为所有实例中的TextBox,并将DependencyProperty附加到新事件。

The pattern for extending it to other controls like you need to do is easy too. I managed to wire up ListBox.SelectionChanged the same way. Create a new ControlBehaviour class and substitute "Control" for "TextBox" in all the instances and attach the DependencyProperty to the new event.

当您的代码是一件美丽的事情后面是空的!

It is a beautiful thing when your code behind is empty!

这篇关于如何附加命令来检查和取消选中CheckBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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