从 XAML 调用位于类中的事件或方法
您好,我正在尝试是否有可能将像 TextChanged (文本框的)这样的事件位于独立于窗口代码隐藏(如类)的另一个位置。
我想做的是在 ResourceDictionary 中引用 TextBox 的事件。 (因为 ResourcesDictionaries 没有 CodeBehind。)
注意:确实必须采用这种方式,因为我正在自定义另一个控件以动态地拥有一些 TextBox,并且当 TextChanged 发生时所有 TextBox 都会触发相同的事件。
Hi i am trying if it's possible having an Event like TextChanged (of a TextBox) located in another place independent of the Window CodeBehind (like a Class).
What i am trying to do is having in the ResourceDictionary a reference to an event of the TextBox. (Because the ResourcesDictionaries doesn't have a CodeBehind.)
Note: It really have to be by this way, because i am customizing another control to have some TextBoxes dynamically and all the TextBoxes will fire the same event when TextChanged occurs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会建议触发器。您可以在这里阅读有关它们的更多信息: http://www .silverlightshow.net/items/Behaviors-and-Triggers-in-Silverlight-3.aspx
本质上,您可以在 xaml 中将控件的事件挂钩到触发器,并让它在其他位置执行方法或命令。
编辑:我应该注意到,虽然它确实说“Silverlight”,但它也适用于 WPF。
Edit2:MVVM工具包提供了一个EventToCommandTrigger,可以让你做这样的事情:
http://blog.galasoft.ch/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx< /a>
感谢 HB 的回答,提醒我执行此操作的命令方式
Edit3:更好的例子,这很大程度上借鉴了 MVVM 世界的做法。由于 EventToCommand 绑定将附加到控件的上下文,因此您可以将其粘贴在 ResourceDictionary 中以及放置它的任何位置,它会尝试查找 TextChangeCommand 属性。
和隐藏代码:
I would suggest triggers. You can read more about them here: http://www.silverlightshow.net/items/Behaviors-and-Triggers-in-Silverlight-3.aspx
Essentially you can, in xaml, hook a control's event to a trigger and have it execute a method or command else where.
Edit: I should note that while it does say 'Silverlight' it all applies to WPF as well.
Edit2: The MVVM toolkit provides an EventToCommandTrigger that would let you do something like this:
http://blog.galasoft.ch/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx
Kudos to H.B.'s answer for reminding me about the command way of doing this
Edit3: Better example, this borrows heavily from how the MVVM world would do this. Since the EventToCommand binding would attached to whatever the control's context is, you could stick this in your ResourceDictionary and anywhere you place it, it would attempt to find that TextChangeCommand property.
and the codebehind:
编辑: 除非您想子类化 TextBox 以在 TextChanged 上执行命令,否则请忽略此设置。 (我认为触发方法是首选。)
我建议使用命令;在某处定义一个 RoutedCommand:
将其设置为字典中的按钮:
并创建一个命令绑定:
Edit: Disregard this unless you want to subclass TextBox to execute a command on TextChanged. (I think the trigger-method is to be preferred.)
I would suggest Commands for this; define a RoutedCommand somewhere:
Set it to the button in the dictionary:
And create a command binding: