tags:

views:

408

answers:

4

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.

A: 

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.

Randolpho
Could you explain, why subclassing TextBox (or any other control) may be a bad idea?
Treb
+1  A: 

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.

Charlie
Works for me. That way I can just declare one style and have it affect every textbox without having to modify other my other resources.
Steve the Plant
+2  A: 

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.

HTH, Kent

Kent Boogaart
My textboxes are databound to properties that continously get updated. Whenever a textbox is in focus, even if the user tries to type something, the textbox's text gets set to the property's value. What the GotFocus and LostFocus events would do is to enable and disable databinding temporarily while the user is typing.
Steve the Plant
An attached behavior sounds more appropriate for your needs. Updating my post...
Kent Boogaart
A: 

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:

http://www.highoncoding.com/Articles/578_Creating_WPF_TextBox_UserControl_to_Perform_Custom_Validation.aspx

azamsharp