Blogs

Modfying WPF Textbox or Other Control Behavior

17 Apr

So as I have mentioned in previous blog postings and on Twitter, I have been working a lot more recently in WPF than in recent months due to a big project I had been completing. One of the final "Client Review" items that I had to resolve was that they didn't like the way that the textboxes worked. The default behavior for textboxes in WPF when tabbing into them was to put the cursor at the beginning of the field. I agree that the usability was not good, but I had over 400 textboxes and didn't want to have to change all of them. SO I went digging for a solution....

Event Manager

After a bit of digging, I stumbled across the EventManager class that allows you to register handlers for classes. Looking through the MSDN documentation I found that I could pass it a type, the event, and the handler to register. Then any time a control was instantiated the handler would be registered.

Using this I was able to add a handler to the "GotFocus" event of the TextBox control. To meet my client needs I simply had it "SelectAll" text in the box. Now this could be used with any other options or customer code to add behaviors across an entire application. To ensure that this was wired up in the proper location I added the code in the "OnStartup" method of app.zaml.cs, the following code is what was added:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    EventManager.RegisterClassHandler(typeof(TextBox), 
    TextBox.GotFocusEvent, 
    new RoutedEventHandler(TextBox_GotFocus));
}
 
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).SelectAll();
}

As you can see a simple single method call to register a class handler and my desired functionality was implemented, all 400+ TextBox controls in my application were updated and the customer was happy!.

I hope this quick WPF tip helps you out. Feel free to comment below.

tags: .NET 4.0, WPF, Quick Tips
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Connect with Mitchel

I hope the information here has been helpful. To stay connected you can also subscribe to blog updates via email, contact Mitchel about consulting services, or reach out for assistance via CodeMendor

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.