I want keyboard focus to be set to a TextBox when I click a Button on my view. I don't want to use any codebehind, so wondered if anyone had written an attached property or similar solution?
Asked
Active
Viewed 3,975 times
1 Answers
5
Try this out:
public static class FocusBehavior
{
public static readonly DependencyProperty ClickKeyboardFocusTargetProperty =
DependencyProperty.RegisterAttached("ClickKeyboardFocusTarget", typeof(IInputElement), typeof(FocusBehavior),
new PropertyMetadata(OnClickKeyboardFocusTargetChanged));
public static IInputElement GetClickKeyboardFocusTarget(DependencyObject obj)
{
return (IInputElement)obj.GetValue(ClickKeyboardFocusTargetProperty);
}
public static void SetClickKeyboardFocusTarget(DependencyObject obj, IInputElement value)
{
obj.SetValue(ClickKeyboardFocusTargetProperty, value);
}
private static void OnClickKeyboardFocusTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var button = sender as ButtonBase;
if (button == null)
return;
if (e.OldValue == null && e.NewValue != null)
button.Click += OnButtonClick;
else if (e.OldValue != null && e.NewValue == null)
button.Click -= OnButtonClick;
}
private static void OnButtonClick(object sender, RoutedEventArgs e)
{
var target = GetKeyboardClickFocusTarget((ButtonBase)sender);
Keyboard.Focus(target);
}
}
Then to use it,
<TextBox x:Name="TargetTextBox"/>
<Button b:FocusBehavior.ClickKeyboardFocusTarget="{Binding ElementName=TargetTextBox}"/>

Daniel Moore
- 1,116
- 1
- 9
- 16
-
Thanks, that's given me a head start! – devdigital Jan 15 '11 at 14:26
-
This example is working fine. However, there is small change in the following method. You have to call the `GetClickKeyboardFocusTarget` method instead of `GetKeyboardClickFocusTarget`: private static void OnButtonClick(object sender, RoutedEventArgs e) { var target = GetKeyboardClickFocusTarget((ButtonBase)sender); Keyboard.Focus(target); } – Jul 12 '11 at 14:11