附加属性更新样式触发事件

mor*_*are 9 c# wpf

我正在尝试使用附加属性来触发UIElement事件触发时的样式更改.

以下是案例情景:

用户看到a TextBox,然后聚焦然后解开它.在附加属性的某处,它会注意到这个LostFocus事件,并设置一个属性(某处?)来表示它HadFocus.

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>
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一些附加属性的组合来使这个工作,我的最新尝试抛出一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有人能指导我吗?

Cle*_*ens 5

注册只读依赖项属性并不意味着要添加Key到属性名称.只需更换

DependencyProperty.RegisterAttachedReadOnly("HadFocusKey", ...);
Run Code Online (Sandbox Code Playgroud)

通过

DependencyProperty.RegisterAttachedReadOnly("HadFocus", ...);
Run Code Online (Sandbox Code Playgroud)

因为HadFocus是财产的名称.