WPF中的基类DependencyProperty值更改 [英] Base class DependencyProperty value change in WPF

查看:37
本文介绍了WPF中的基类DependencyProperty值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ClassA中有一个DependencyProperty。我从ClassA派生了另一个ClassB。在ClassA中更新或更改此属性的值时,如何在不向ClassA中添加任何附加代码的情况下在派生的ClassB中通知或反映该属性?

I have a DependencyProperty in the ClassA. I derived another ClassB from ClassA. When the value of this property is updated or changed in ClassA, How it can be notified or reflected in the derived ClassB with out adding any additional code in ClassA ?

推荐答案

如果您希望在两个类中都引发属性更改,则可以添加另一个所有者。

If you want the property change to be raised in both classes you can add another owner.

using System.Windows;

namespace dp
{
    public class ClassA : DependencyObject
    {
        public string TestProperty
        {
            get { return (string)GetValue(TestPropertyProperty); }
            set { SetValue(TestPropertyProperty, value); }
        }
        public static readonly DependencyProperty TestPropertyProperty =
            DependencyProperty.Register("TestProperty", typeof(string), typeof(ClassA), new PropertyMetadata(null, new PropertyChangedCallback( (s, e)=>
                {
                })));
    }

    public class ClassB : ClassA
    {
        static ClassB()
        {
            TestPropertyProperty.AddOwner(typeof(ClassB), new PropertyMetadata((s, e) =>
                {
                }));
        }    
    }

    public partial class MainWindow : Window
    {
        public ClassB TestClassB
        {
            get { return (ClassB)GetValue(TestClassBProperty); }
            set { SetValue(TestClassBProperty, value); }
        }        
        public static readonly DependencyProperty TestClassBProperty =
            DependencyProperty.Register("TestClassB", typeof(ClassB), typeof(MainWindow), new PropertyMetadata(null));


        public MainWindow()
        {
            InitializeComponent();
            TestClassB = new ClassB();
            TestClassB.TestProperty = "test";
        }
    }
}

这篇关于WPF中的基类DependencyProperty值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆