【WPF】キーボードフォーカスが当たらない


ウィンドウ初期表示時に、ある要素にキーボードフォーカスを当てたいのに当たりません。

以下やってみたこと。

  • FocusManager.FocusedElement="{Binding ElementName=ButtonOk}"
  • Focusableをtrueにする
  • Keyboard.Focus()をActivatedイベントに登録

しかし思うように動作せずハマってましたが、こちらにどんぴしゃの解決法が載ってました。
https://stackoverflow.com/questions/20294658/focusedelement-is-not-being-honoured

備忘録として載せておきます。

class
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);
        }
    }
}
xaml
<UserControl xmlns:behaviors="clr-namespace:Invoices.Client.Wpf.Behaviors">
    <Grid behaviors:KeyboardFocus.On="{Binding ElementName=TextBoxToFocus}">
        <TextBox x:Name="TextBoxToFocus" />
    </Grid>
</UserControl>

私の場合はこれで無事解決しました。