Reputation: 12832
I have an application that declares textboxes in various places, like in styles and datatemplates, and now I'm in a situation where I need to change every textbox's standard behavior for getting and losing focus.
What's a good way to do this?
I was thinking of two solutions: one is to derive a new class from TextBox, which I understand is generally frowned upon. The other is to create some kind of style that uses EventSetters, but since the styles and datatemplates in my application don't have codebehind files I donno how an event will find the appropriate event handler.
Upvotes: 1
Views: 1217
Reputation: 178780
Based on your feedback, I'd recommend an attached behavior used as follows:
<TextBox b:TextBox.SuppressOnFocus="True"/>
The attached behavior implementation would simply attach to GotFocus and LostFocus and clear/reapply the binding as appropriate.
Upvotes: 2
Reputation: 20096
If you are going to use this functionality in only one project then you can create UserControls which has a TextBox and access the the OnFocus properties. You can also make a Custom WPF Control which derives from a TextBox and then implement the LocusFocus event.
I have used the same approach to create a User Control TextBox which performs validation:
Upvotes: 0
Reputation: 15247
You can create a style that applies to all TextBoxes using the Key property as follows:
<Style x:Key={x:Type TextBox}>
...
</Style>
You can then modify the Template property of the TextBox and use Triggers to add special behavior to the OnGotFocus and OnLostFocus events.
Upvotes: 2
Reputation: 56439
Under normal circumstances, I, too, would frown upon subclassing TextBox. In this case, since you are changing the behavior of the TextBox, a subclass may be your best option.
Upvotes: 0