Jam*_*mes 3 c# wpf dependency-properties
我在ClassA中有一个DependencyProperty.我从ClassA派生了另一个ClassB.在ClassA中更新或更改此属性的值时,如何在派生的ClassB中通知或反映它,而不在ClassA中添加任何其他代码?
通过派生类中的DependencyProperty.OverrideMetadata为ClassB注册PropertyChangedCallback :
class ClassB
{
static ClassB()
{
ClassA.SomeValueProperty.OverrideMetadata(
typeof(ClassB), new PropertyMetadata(SomeValuePropertyChanged);
}
private static SomeValuePropertyChanged(
DependencyObject o, DependencyPropertyChangedArgs e)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果要在两个类中引发属性更改,则可以添加另一个所有者。
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)