WPF: Setting Keyboard Focus in a User Control? (Problems with KeyBinding)

For me this worked in the code-behind:

using System.Windows.Input;

namespace MyApplication.Views.Dialogs
{
    public partial class MyControl
    {
        public MyControl()
        {
            InitializeComponent();
            Loaded += (sender, args) =>
            {
                MyButton.Focus();
                Keyboard.Focus(MyButton);
            };
        }
    }
}

I wanted this control to have the focus, when it became visible. So in the constructor, I set up a handler on IsVisibleChanged.

public MyControl
{
    ...
    this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(MyControl_IsVisibileChanged);
}

void MyControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (!(bool(e.NewValue)
        return;
    this.Focusable = true;
    Keyboard.Focus(this);
}

I could have set Focusable in the xaml, but I prefer it in the code-behind, so that all of the relevant code is in one place.

Tags:

Wpf

Xaml

Focus