Quantcast
Viewing latest article 3
Browse Latest Browse All 13

Answer by Drew Noakes for WPF and initial focus

A minimal version of Mizipzor's answer for C# 6+.

public static class FocusBehavior{    public static readonly DependencyProperty GiveInitialFocusProperty =        DependencyProperty.RegisterAttached("GiveInitialFocus",            typeof(bool),            typeof(FocusBehavior),            new PropertyMetadata(false, OnFocusFirstPropertyChanged));    public static bool GetGiveInitialFocus(Control control) => (bool)control.GetValue(GiveInitialFocusProperty);    public static void SetGiveInitialFocus(Control control, bool value) => control.SetValue(GiveInitialFocusProperty, value);    private static void OnFocusFirstPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)    {        var control = obj as Control;        if (control == null || !(args.NewValue is bool))            return;        if ((bool)args.NewValue)            control.Loaded += OnControlLoaded;        else            control.Loaded -= OnControlLoaded;    }    private static void OnControlLoaded(object sender, RoutedEventArgs e) => ((Control)sender).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));}

Use in your XAML:

<Window local:FocusBehavior.GiveInitialFocus="True" />

Viewing latest article 3
Browse Latest Browse All 13

Trending Articles



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