Quantcast
Channel: WPF and initial focus - Stack Overflow
Viewing all articles
Browse latest Browse all 13

Answer by Mizipzor for WPF and initial focus

$
0
0

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.First));            }        }    }}

Use it like this:

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

Viewing all articles
Browse latest Browse all 13

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>