wpf viewmodel中控制页面焦点

发布时间 2023-09-22 11:05:20作者: Hey,Coder!
public static class FocusBehavior
    {
        private static Dictionary<UIElement, RoutedEventHandler> handlers = new Dictionary<UIElement, RoutedEventHandler>();
        public static bool? GetIsFocused(DependencyObject obj)
        {
            return (bool?)obj.GetValue(IsFocusedProperty);
        }
        public static void SetIsFocused(DependencyObject obj, bool? value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }
        public static readonly DependencyProperty IsFocusedProperty =
                    DependencyProperty.RegisterAttached(
                    "IsFocused",
                    typeof(bool?),
                    typeof(FocusBehavior),
                    new UIPropertyMetadata()
                    {
                        DefaultValue = null,
                        PropertyChangedCallback =
                            (s, e) =>
                            {
                                UIElement sender = (UIElement)s;
                                RoutedEventHandler x;
                                if (!handlers.TryGetValue(sender, out x))
                                {
                                    Attach(sender);
                                }
                                if ((bool)e.NewValue)
                                {
                                    sender.Focus();
                                    Keyboard.Focus(sender);
                                }
                            }
                    });
        private static void Attach(UIElement sender)
        {
            RoutedEventHandler handler = (s, e) =>
            {
                UIElement ui = (UIElement)s;
                if (e.RoutedEvent == UIElement.GotFocusEvent)
                {
                    ui.SetValue(IsFocusedProperty, true);
                }
                if (e.RoutedEvent == UIElement.LostFocusEvent)
                {
                    ui.SetValue(IsFocusedProperty, false);
                }
            };
            sender.GotFocus += handler;
            sender.LostFocus += handler;
            handlers.Add(sender, handler);
        }
    }

注意引用名称空间

             xmlns:localHelper="clr-namespace:Test.Helper"

页面绑定此属性,注意需要双向绑定

<TextBox TabIndex="4" localHelper:FocusBehavior.IsFocused="{Binding ISFocusable5,Mode=TwoWay}"/>

[参考]
C# WPF MVVM 实战 – 5- 用绑定,通过 VM 设置 View 的控件焦点