【问题标题】:Setting focus from viewmodel does not work properly从 viewmodel 设置焦点无法正常工作
【发布时间】:2014-05-20 21:47:33
【问题描述】:

我正在尝试从 viewmodel 为某个 UIElement 依赖对象设置焦点,为此我编写了一个附加依赖属性,如下所示:

    #region IsFocusedProperty
    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(AttachedProperties),
        new FrameworkPropertyMetadata(false,
            new PropertyChangedCallback(OnIsFocusedChanged)));

    private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var obj = d as UIElement;

        var oldValue = (bool)e.OldValue;
        var newValue = (bool)e.NewValue;

        if (oldValue != newValue && !obj.IsFocused)
        {
            obj.Focus();
        }
    }

    public static void SetIsFoused(UIElement element, bool value)
    {
        element.SetValue(IsFocusedProperty, value);
    }

    public static bool GetIsFocused(UIElement element)
    {
        return (bool)element.GetValue(IsFocusedProperty);
    }
    #endregion

我应该说它可以工作并将焦点发送到指定元素,除非当我将鼠标光标移动到视图中的每个元素(包括焦点所在的指定元素)上时没有触发鼠标事件。我这样说是因为我已经为元素的 IsMouseOverProperty 编写了触发器,但是当以这种方式将焦点发送到指定元素时没有任何反应。

我还应该说,当我单击视图上的任意位置时,触发器再次正常工作。我真的不知道是什么问题?请分享你的想法。任何想法将不胜感激。提前致谢。

编辑: 我发现该元素接收键盘焦点但显然不是逻辑焦点,因为当我将光标移动到前一个元素时,它仍然会触发 MouseMove 事件。

我仍然不确定问题是什么?

【问题讨论】:

    标签: c# wpf focus viewmodel


    【解决方案1】:

    更新到:

    if (oldValue != newValue && !obj.IsFocused)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Input,
            new Action(delegate() 
            { 
                obj.Focus();        
                Keyboard.Focus(obj); 
            })
        );
    }
    

    【讨论】:

    • 感谢@d.moncada,但它仍然无法正常工作。
    猜你喜欢
    • 2017-06-10
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2021-10-15
    • 2022-08-17
    相关资源
    最近更新 更多