Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class DependencyProperty value change in WPF

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 ?

like image 670
James Avatar asked Oct 24 '13 08:10

James


2 Answers

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";
        }
    }
}
like image 33
Andy Avatar answered Oct 23 '22 15:10

Andy


By registering a PropertyChangedCallback for ClassB through DependencyProperty.OverrideMetadata in the derived class:

class ClassB
{
    static ClassB()
    {
        ClassA.SomeValueProperty.OverrideMetadata(
            typeof(ClassB), new PropertyMetadata(SomeValuePropertyChanged);
    }

    private static SomeValuePropertyChanged(
        DependencyObject o, DependencyPropertyChangedArgs e)
    {
        ...
    }
}
like image 173
Clemens Avatar answered Oct 23 '22 17:10

Clemens