开发者

How to constrain Attached Properties to only the children of one container class?

开发者 https://www.devze.com 2023-03-07 03:44 出处:网络
Given this code below, how one would enrich the class so as to constrain this attached property to only the children of one precise container ( lets call it \"class MyContainer\") ), just the way thin

Given this code below, how one would enrich the class so as to constrain this attached property to only the children of one precise container ( lets call it "class MyContainer") ), just the way things are going with Canvas X and Y and also Grid Column and Row attached properties.

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.Ge开发者_运维百科tValue(MyAttachedProperty);
    }

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

}


Attached Properties BY DEFINITION can be attached to any class that implements DependencyObject.

You can change the implementation of the getters and setters like so:

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

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

so they will only target MyContainer, but that won't really help as the real work is done in the underlying obj.SetValue / obj.GetValue, which WPF will call directly many times.

The best solution is to use to define a Behavior<MyContainer> and that can be attached ONLY to MyContainer. Behaviors are just sophisticated & more elegant Attached Properties, so eveything else would stay pretty much the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消