WPF/XAML : multiple controls using the same events - is there an easier way?

标签 wpf events templates xaml controls

我有大约 10 个使用相同事件的文本框 - 然后我只是将 sender 转换为文本框并对文本进行任何更改。我很好奇,有没有更简单/更简洁的方法将这些事件分配给代码隐藏方法?现在,我只是通过将每个事件的方法重复分配给每个文本框来做到这一点。

有什么可以用模板或任何东西来完成的吗?下面是每个文本框上的内容。这只是复制和粘贴,但它有很多额外的代码行,如果有 WPF 解决方案,我想避免它。

...
LostFocus="textBox_LostFocus"
MouseDoubleClick="selectText"
GotKeyboardFocus="selectText"
PreviewMouseLeftButtonDown="selectivelyIgnoreMouseButton" />

提前致谢。

最佳答案

是的,有更好的方法。为文本框创建样式。

<Style TargetType="{x:Type TextBox}">
    <EventSetter Event="LostFocus" Handler="textBox_LostFocus" />
    <EventSetter Event="MouseDoubleClick" Handler="selectText" />
    <EventSetter Event="GotKeyboardFocus" Handler="selectText" />
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="selectivelyIgnoreMouseButton" />
</Style>

Here's一篇简单的博客文章,解释了更多相关信息。

关于WPF/XAML : multiple controls using the same events - is there an easier way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7196456/

相关文章:

c# - 从父 View 模型派生的空 ViewModel 是否存在问题? WPF

c# - 我应该绑定(bind)到 ICollectionView 还是 ObservableCollection

wpf - WPF 的 Control.FromHandle

javascript - Firefox 中文本框的 onpropertychange?

c# - "object sender"和 "EventArgs e"参数有什么用?

c++ - 限制基本模板实例化

c++ - C++ 模板的实例化惰性规则

c# - 具有不同方向的 WPF 虚拟化 TreeView 不虚拟化?

c# - 跟踪 PRISM/CAL 事件(最佳实践?)

javascript - Web 组件模板错误