如何将附加属性仅限制为一个容器类的子项?

时间:2011-05-18 09:20:21

标签: c# wpf xaml attached-properties

鉴于下面的代码,如何丰富类,以便将这个附加属性限制为只有一个精确容器的子项(让我们称之为“类MyContainer”)),就像Canvas X和Y以及Grid Column和Row附加属性。

public class MyAttachedPropertyClass
{
    public static readonly DependencyProperty MyAttachedProperty;
    static MyAttachedPropertyClass()
    {
        MyAttachedProperty= DependencyProperty.RegisterAttached("MyAttached",
                                                            typeof(MyProperty),
                                                            typeof(MyAttachedPropertyClass),
                                                            new PropertyMetadata(null);
    }

    public static MyProperty GetTitleText(DependencyObject obj)
    {
        return (MyProperty)obj.GetValue(MyAttachedProperty);
    }

    public static void SetTitleText(DependencyObject obj, MyProperty value)
    {
        obj.SetValue(MyAttachedProperty, value);
    }
}

}

1 个答案:

答案 0 :(得分:1)

附加属性BY DEFINITION可以附加到任何实现DependencyObject的类。

您可以像这样更改getter和setter的实现:

public static MyProperty GetTitleText(MyContainer obj)
{
    return (MyProperty)obj.GetValue(MyAttachedProperty);
}

public static void SetTitleText(MyContainer obj, MyProperty value)
{
    obj.SetValue(MyAttachedProperty, value);
}

因此他们只会定位MyContainer,但这并不会真正有用,因为真正的工作是在底层的obj.SetValue / obj.GetValue中完成的,WPF将直接调用多次。

最佳解决方案是使用定义Behavior<MyContainer>并且只能附加到MyContainer。行为只是复杂而且更优雅的附属物,所以其他东西会保持不变。

相关问题