0

我正在开发一个avalonia wpf 应用程序,并且我注册了一个 AttachedProperty“IsFocused”,如下所示:

public class FocusExtension
{
    public static readonly AttachedProperty<bool> IsFocusedProperty =
        AvaloniaProperty.RegisterAttached<Control, bool>("IsFocused", typeof(FocusExtension));

    public static bool GetIsFocused(Control element)
    {
        return element.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(Control element, bool value)
    {
        element.SetValue(IsFocusedProperty, value);
        OnIsFocusedPropertyChanged(element, value);
    }

    private static void OnIsFocusedPropertyChanged(
        Control element,
        bool e)
    {
        if (e)
        {
            element.Focus();
        }
    }
}

并像这样在xaml中应用它:

  <Button Content="Test" u:FocusExtension.IsFocused="{Binding SomeBoolPropertyInViewModel}"/>

但是当我的 ViewModel 将“SomeBoolPropertyInViewModel”设置为 true 时,它​​似乎不起作用,

有人可以给我一个例子或提示来实施这项工作吗?谢谢。

4

1 回答 1

0

不能保证SetIsFocused会被调用,因为element.SetValue(IsFocusedProperty, value)可以直接调用。因此,您必须在静态构造函数中为属性更改事件添加一个处理程序:

static FocusExtension()
{
    IsFocusedProperty.Changed.AddClassHandler<Control>(OnIsFocusedPropertyChanged);
}

private static void OnIsFocusedPropertyChanged(
    Control element,
    AvaloniaPropertyChangedEventArgs e)
{
    if ((bool)e.NewValue)
    {
        element.Focus();
    }
}
于 2021-02-06T16:26:08.420 回答