Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 788
Yatrix Avatar asked Aug 25 '11 19:08

Yatrix


1 Answers

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.

like image 182
Dylan Meador Avatar answered Nov 02 '22 23:11

Dylan Meador