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.
精彩评论