TextBox.TextChanged& ICommandSource [英] TextBox.TextChanged & ICommandSource

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

问题描述

我遵循 MV-VM 模式为我的WPF UI。我想挂钩一个TextChanged事件的TextBox的命令到我的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?

推荐答案

首先,你一定认为双向数据绑定到你的viewmodel, 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的博客中,您会发现一个

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)中,这是一个非常类似于Silverlight的东西,它应该很容易适应WPF。您定义一个名为(或许)TextChangedCommand的类型ICommand的附加属性。为该属性挂接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已经分配给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; ICommandSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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