如何将附加属性限制为仅一个容器类的子级?
给定下面的这段代码,我们将如何丰富该类,以便将该附加属性限制为仅一个精确容器的子级(我们称之为“类 MyContainer”)),就像 Canvas X 和 Y 的情况一样网格列和行附加属性。
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);
}
}
}
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.GetValue(MyAttachedProperty);
}
public static void SetTitleText(DependencyObject obj, MyProperty value)
{
obj.SetValue(MyAttachedProperty, value);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据定义附加属性可以附加到任何实现 DependencyObject 的类。
您可以像这样更改 getter 和 setter 的实现:
这样它们只会针对 MyContainer,但这并没有真正的帮助,因为真正的工作是在底层 obj.SetValue / obj.GetValue 中完成的,WPF 将直接调用许多次。
最好的解决方案是定义一个
Behavior
并且只能附加到 MyContainer。行为非常复杂且复杂。更优雅的附加属性,因此其他所有内容都几乎保持不变。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:
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.