Back to all posts

Modifying WPF TextBox or Other Control Behavior

Posted on Apr 17, 2011

Posted in category:
Development
Windows

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 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 custom 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:

Event Manager Example
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.