Setting the Keyboard Focus in WPF
There’s nothing more annoying that trying to fill a form and having to reach the mouse and click on a text box. I’m currently working on an invoicing application in which the user has to manually input a lot of info in a wizard-like screens workflow. Should she had to grab the mouse when a new screen loads and click on the first text box, she’d be (deservedly) cursing me more often than not.
So I decided to create an attached property which sets the keyboard focus on the specified element:
namespace Invoices.Client.Wpf.Behaviors
{
using System.Windows;
using System.Windows.Input;
public static class KeyboardFocus
{
public static readonly DependencyProperty OnProperty;
public static void SetOn(UIElement element, FrameworkElement value)
{
element.SetValue(OnProperty, value);
}
public static FrameworkElement GetOn(UIElement element)
{
return (FrameworkElement)element.GetValue(OnProperty);
}
static KeyboardFocus()
{
OnProperty = DependencyProperty.RegisterAttached("On", typeof(FrameworkElement), typeof(KeyboardFocus), new PropertyMetadata(OnSetCallback));
}
private static void OnSetCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var frameworkElement = (FrameworkElement)dependencyObject;
var target = GetOn(frameworkElement);
if (target == null)
return;
frameworkElement.Loaded += (s, e) => Keyboard.Focus(target);
}
}
}
And here’s how to use it in xaml:
<UserControl mlns:behaviors="clr-namespace:Invoices.Client.Wpf.Behaviors" >
<Grid behaviors:KeyboardFocus.On="{Binding ElementName=TextBoxToFocus}">
<TextBox x:Name="TextBoxToFocus" />
</Grid>
</UserControl>
This will definitely help your user doing her job quicker and easier. And don’t forget to set the IsDefault and IsCancel properties in your form’s default buttons. That’ll make a difference for shortcut freaks like me!
