首页 > 解决方案 > 当用户控件失去焦点时更新 Viewmodel 属性

问题描述

<UserControl  UIHelper:FocusExtension.IsFocused="{Binding FocusUserControl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Focusable="True" IsTabStop="True">

这里我添加了一个 IsFocused 道具来保持用户控件的焦点

 public static class FocusExtension
    {
        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(FocusExtension),
                new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

        private static void OnIsFocusedPropertyChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                 uie.Focus();
            }
        }
    }

这是我的 FocusExtension 课程

public bool FocusUserControl
        {
            get { return focusUserControl; }
            set
            {
                focusUserControl = value;
                OnPropertyChanged(new PropertyChangedEventArgs("FocusUserControl"));
            }
        }

这是我的虚拟机道具。这是绑定的,现在在用户控制中,我有一个按钮。当我单击它时,将出现一个新的用户控件。打开那个时候我需要更新FocusUserControl为false。因为 焦点不再是那个用户控件了。我被困在这里,请提出一些建议,感谢您的帮助。

**

更新我添加了这样的东西

**

 private static void OnIsFocusedPropertyChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                uie.LostKeyboardFocus += LostFocus;
                uie.Focus();
            }

        }
        static void LostFocus(object sender, RoutedEventArgs e)
        {
            uie.LostKeyboardFocus -= LostFocus;
            // Here i need to update `FocusUserControl` to false 
        }

在 LostFocus 中,我只需要更新FocusUserControl为 false。我该怎么做?真的需要一些帮助。

标签: c#.netwpfmvvmfocus

解决方案


推荐阅读