在事件上附加属性以更新样式触发器

9
我试图使用一个附加属性来触发 UIElement 在事件被触发时的样式更改。
以下是情况的场景:
用户看到一个TextBox,并将其聚焦,然后取消聚焦。在某个附加属性中,它注意到了这个LostFocus事件并将一个属性设置为(某处?)表示它曾经聚焦。
然后,TextBox上的样式知道它应该根据这个 HadFocus 属性不同地进行样式设计。
这是我想象中标记的样子...
<TextBox Behaviors:UIElementBehaviors.ObserveFocus="True">
<TextBox.Style>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="Behaviors:UIElementBehaviors.HadFocus" Value="True">
                <Setter Property="Background" Value="Pink"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

我尝试了几种组合来使它工作,我最新的尝试抛出一个 XamlParseException,指出“触发器的属性不能为空。”


    public class UIElementBehaviors
{
    public static readonly DependencyProperty ObserveFocusProperty =
        DependencyProperty.RegisterAttached("ObserveFocus",
                                            typeof (bool),
                                            typeof (UIElementBehaviors),
                                            new UIPropertyMetadata(false, OnObserveFocusChanged));
    public static bool GetObserveFocus(DependencyObject obj)
    {
        return (bool) obj.GetValue(ObserveFocusProperty);
    }
    public static void SetObserveFocus(DependencyObject obj, bool value)
    {
        obj.SetValue(ObserveFocusProperty, value);
    }

    private static void OnObserveFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = d as UIElement;
        if (element == null) return;

        element.LostFocus += OnElementLostFocus;
    }
    static void OnElementLostFocus(object sender, RoutedEventArgs e)
    {
        var element = sender as UIElement;
        if (element == null) return;

        SetHadFocus(sender as DependencyObject, true);

        element.LostFocus -= OnElementLostFocus;
    }

    private static readonly DependencyPropertyKey HadFocusPropertyKey =
        DependencyProperty.RegisterAttachedReadOnly("HadFocusKey",
                                                    typeof(bool),
                                                    typeof(UIElementBehaviors),
                                                    new FrameworkPropertyMetadata(false));

    public static readonly DependencyProperty HadFocusProperty = HadFocusPropertyKey.DependencyProperty;
    public static bool GetHadFocus(DependencyObject obj)
    {
        return (bool)obj.GetValue(HadFocusProperty);
    }

    private static void SetHadFocus(DependencyObject obj, bool value)
    {
        obj.SetValue(HadFocusPropertyKey, value);
    }
}

有人能指导我吗?
1个回答

5
注册只读依赖属性并不意味着要在属性名称中添加“Key”。只需替换即可。
DependencyProperty.RegisterAttachedReadOnly("HadFocusKey", ...);

by

DependencyProperty.RegisterAttachedReadOnly("HadFocus", ...);

因为HadFocus是该属性的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接