1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

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

以下やってみたこと。

  • 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>

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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?