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

时间:2012-05-22 13:47:24

标签: c# wpf

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

以下是案例情景:

用户看到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>

我尝试了一些附加属性的组合以使其正常工作,我的最新尝试抛出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 个答案:

答案 0 :(得分:5)

注册只读依赖项属性并不意味着将Key添加到属性名称。只需替换

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

通过

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

因为HadFocus是属性的名称。