C# WPF:自定义DependencyObjects的值继承?
我正试图为自定义WPF DependencyObject中的DependencyProperty实现值继承,但我遇到了严重的问题:( 我想做什么: 我有两个类T1和T2,它们都有DependencyProperty IntTest,默认值为0。T1应该是T2的根,就像窗口是它包含的文本框的逻辑根/父对象一样 因此,当我没有明确设置T2.IntTest的值时,它应该提供T1.IntTest的值(就像例如TextBox.FlowDirection通常提供父窗口的FlowDirection) 我所做的: 我创建了从FrameworkElement派生的两个类T1和T2,以便将FrameworkPropertyMetadata与FrameworkPropertyMetadataOptions.Inherits一起使用。我还了解到,为了使用值继承,必须将DependencyProperty设计为AttachedProperty 当前,当我为根T1赋值时,子T2的DP Getter不会返回该值 我做错了什么 这是两类:C# WPF:自定义DependencyObjects的值继承?,c#,wpf,inheritance,dependency-properties,dependencyobject,C#,Wpf,Inheritance,Dependency Properties,Dependencyobject,我正试图为自定义WPF DependencyObject中的DependencyProperty实现值继承,但我遇到了严重的问题:( 我想做什么: 我有两个类T1和T2,它们都有DependencyProperty IntTest,默认值为0。T1应该是T2的根,就像窗口是它包含的文本框的逻辑根/父对象一样 因此,当我没有明确设置T2.IntTest的值时,它应该提供T1.IntTest的值(就像例如TextBox.FlowDirection通常提供父窗口的FlowDirection) 我所做的
// Root class
public class T1 : FrameworkElement
{
// Definition of an Attached Dependency Property
public static readonly DependencyProperty IntTestProperty = DependencyProperty.RegisterAttached("IntTest", typeof(int), typeof(T1),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
// Static getter for Attached Property
public static int GetIntTest(DependencyObject target)
{
return (int)target.GetValue(IntTestProperty);
}
// Static setter for Attached Property
public static void SetIntTest(DependencyObject target, int value)
{
target.SetValue(IntTestProperty, value);
}
// CLR Property Wrapper
public int IntTest
{
get { return GetIntTest(this); }
set { SetIntTest(this, value); }
}
}
// Child class - should inherit the DependenyProperty value of the root class
public class T2 : FrameworkElement
{
public static readonly DependencyProperty IntTestProperty = T1.IntTestProperty.AddOwner(typeof(T2),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
public int IntTest
{
get { return (int)GetValue(IntTestProperty); }
set { SetValue(IntTestProperty, value); }
}
}
下面是试用的代码:
T1 t1 = new T1();
T2 t2 = new T2();
// Set the DependencyProperty of the root
t1.IntTest = 123;
// Do I have to build a logical tree here? If yes, how?
// Since the DependencyProperty of the child was not set explicitly,
// it should provide the value of the base class, i.e. 123.
// But this does not work: i remains 0 :((
int i = t2.IntTest;
附加属性的关键属性是,它可以(通常是)在与其设置对象不同的对象上声明。在这种情况下,您已经在
T1
上声明了所需的所有内容,但您应该在那里停止(尽管要去掉IntTest
属性包装器-AP使用get/set方法)。您还可以在其他帮助器类上声明IntTest
。无论在何处声明,都可以在任何DependencyObject
上设置它
// set on the declaring type
T1.SetIntTest(t1, 123);
// set on your other type
T1.SetIntTest(t2, 456);
// set on any other framework type
Button button = new Button();
T1.SetIntTest(button, 789);
另一个您似乎正在努力解决的问题是设置树。继承作为逻辑层次结构的一部分工作,因此为了从另一个实例继承值,继承对象必须是原始对象的逻辑子对象。由于您是从基本
FrameworkElement
派生的,因此无法获得任何ContentControl
和ItemsControl
内置了子项(分别为单个和多个)的概念,提供了遏制的好处。您试图从使用继承的DPs中获得什么价值?