Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus to a control in WPF using MVVM

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?

like image 857
devdigital Avatar asked Jan 14 '11 17:01

devdigital


People also ask

How do I set focus in WPF MVVM?

How to use this? this. SetFocus(()=>ViewModelProperty); or this. SetFocus("Property");

How do you focus a control in WPF?

When setting initial focus at application startup, the element to receive focus must be in the visual tree of the initial window loaded by the application, and the element must have Focusable and IsVisible set to true . The recommended place to set initial focus is in the Loaded event handler.

Do I have to use MVVM in WPF?

For trivial projects MVVM is unnecessary. Using only the View is sufficient. For simple projects, the ViewModel/Model split may be unnecessary, and just using a Model and a View is good enough. Model and ViewModel do not need to exist from the start and can be introduced when they are needed.


1 Answers

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}"/>
like image 154
Daniel Moore Avatar answered Oct 01 '22 22:10

Daniel Moore