WPF/XAML: multiple controls using the same events - is there an easier way?
I have around 10 textboxes using the same events - I then just cast sender to a textbox and make whatever changes I'm going to make to the text. I'm curious, is there an easier/cleaner way to assign those events to the code-behind methods? Right now, I'm doing it by just assigning each event the method, repeatedly, to each textbox.
Is there anything that can be done with templates or anything? Below is what's on every single TextBox. It's all开发者_如何转开发 just copying and pasting, but it's a lot of extra lines of code and I'd like to avoid it if there's a WPF solution to do so.
...
LostFocus="textBox_LostFocus"
MouseDoubleClick="selectText"
GotKeyboardFocus="selectText"
PreviewMouseLeftButtonDown="selectivelyIgnoreMouseButton" />
Thanks in advance.
Yes, there is a better way. Create a style for the textboxes.
<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 a simple blog post explaining more about it.
精彩评论