WPF and initial focus WPF and initial focus wpf wpf

WPF and initial focus


This works, too:

<Window FocusManager.FocusedElement="{Binding ElementName=SomeElement}">   <DataGrid x:Name="SomeElement">     ...   </DataGrid></Window>


I had the bright idea to dig through Reflector to see where the Focusable property is used, and found my way to this solution. I just need to add the following code to my Window's constructor:

Loaded += (sender, e) =>    MoveFocus(new TraversalRequest(FocusNavigationDirection.First));

This will automatically select the first control in the tab order, so it's a general solution that should be able to be dropped into any window and Just Work.


Based on the accepted answer implemented as an attached behavior:

using System.Windows;using System.Windows.Controls;using System.Windows.Input;namespace UI.Behaviors{    public static class FocusBehavior    {        public static readonly DependencyProperty FocusFirstProperty =            DependencyProperty.RegisterAttached(                "FocusFirst",                typeof(bool),                typeof(FocusBehavior),                new PropertyMetadata(false, OnFocusFirstPropertyChanged));        public static bool GetFocusFirst(Control control)        {            return (bool)control.GetValue(FocusFirstProperty);        }        public static void SetFocusFirst (Control control, bool value)        {            control.SetValue(FocusFirstProperty, value);        }        static void OnFocusFirstPropertyChanged(            DependencyObject obj, DependencyPropertyChangedEventArgs args)        {            Control control = obj as Control;            if (control == null || !(args.NewValue is bool))            {                return;            }            if ((bool)args.NewValue)            {                control.Loaded += (sender, e) =>                    control.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));            }        }    }}

Use it like this:

<Window xmlns:Behaviors="clr-namespace:UI.Behaviors"        Behaviors:FocusBehavior.FocusFirst="true">