Yatrix
Yatrix

Reputation: 13775

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.

Upvotes: 6

Views: 2059

Answers (1)

Dylan Meador
Dylan Meador

Reputation: 2401

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.

Upvotes: 8

Related Questions