TextBox.TextChanged &命令源 [英] TextBox.TextChanged & ICommandSource

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

问题描述

我遵循 MV-VM 模式用于我的 WPF UI.我想将一个命令连接到 TextBox 的 TextChanged 事件到我的 ViewModel 类中的命令.我能想到的完成此任务的唯一方法是从 TextBox 控件继承,并实现 ICommandSource.然后我可以指示从 TextChanged 事件触发命令.对于看起来如此简单的事情来说,这似乎工作量太大了.

I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.

是否有更简单的方法(比继承 TextBox 并实现 ICommandSource)将 TextChanged 事件连接到我的 ViewModel 类?

Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?

推荐答案

首先,您肯定考虑过使用 PropertyChanged 的​​ UpdateSourceTrigger 到视图模型的双向数据绑定吗?这样每次更改文本时都会调用您绑定到的属性的属性设置器?

First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed?

如果这还不够,那么我将使用附加行为来解决这个问题.在 Julian Dominguez 的博客上,您会找到一篇 文章 关于如何在 Silverlight 中做一些非常相似的事情,它应该很容易适应 WPF.

If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an article about how to do something very similar in Silverlight, which should be easily adaptable to WPF.

基本上,在静态类(称为 TextBoxBehaviours)中,您定义一个名为(可能)ICommand 类型的 TextChangedCommand 的附加属性.为该属性连接一个 OnPropertyChanged 处理程序,并在处理程序中检查该属性是否设置在 TextBox 上;如果是,则为文本框上的 TextChanged 事件添加一个处理程序,该处理程序将调用属性中指定的命令.

Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property.

然后,假设您的 viewmodel 已分配给您的 View 的 DataContext,您可以像这样使用它:

Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like:

<TextBox
  x:Name="MyTextBox"
  TextBoxBehaviours.TextChangedCommand="{Binding ViewModelTextChangedCommand}" />

这篇关于TextBox.TextChanged &amp;命令源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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