繁体   English   中英

WPF:值继承自定义DependencyObjects吗?

[英]WPF: Value inheritace for custom DependencyObjects?

我正在尝试在自定义WPF DependencyObject中实现DependencyProperty的值继承,而我的状态很糟:(

我想做的事:

我有两个T1T2类,它们的DependencyProperty IntTest都默认为0。T1应该是T2的根,就像Window是它包含的TextBox的逻辑根/父级一样。

因此,当我没有明确设置T2.IntTest的值时,它应该提供T1.IntTest的值(就像TextBox.FlowDirection通常提供父窗口的FlowDirection一样)。

我做了什么:

为了从FrameworkElement派生出两个类T1和T2,以便将FrameworkPropertyMetadataFrameworkPropertyMetadataOptions.Inherits一起使用。 另外,我读到要使用值继承,必须将DependencyProperty设计为AttachedProperty。

当前,当我为根T1分配一个值时,子T2的DP-Getter不会返回它。

我究竟做错了什么???

这是两个类:

// 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派生的,因此无法获得ContentControlItemsControl所提供的包含遏制的任何好处, ContentControlItemsControl具有内置的子级(分别为单个和多个)概念。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM