[英]WPF - GetBindingExpression in PropertyChangedCallback of DependencyProperty
[英]WPF – Custom Control – Inherited DependencyProperty and PropertyChangedCallback
对于自定义控件 ,如下所示,如何为继承的DependencyProperty IsEnabledProperty添加PropertyChangedCallback ?
public class MyCustomControl : ContentControl
{
// Custom Dependency Properties
static MyCustomControl ()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
// TODO (?) IsEnabledProperty.OverrideMetadata(typeof(MyCustomControl), new PropertyMetadata(true, CustomEnabledHandler));
}
public CustomEnabledHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Implementation
}
}
是的,还有另一种选择,比如听IsEnabledChangeEvent
public class MyCustomControl : ContentControl
{
public MyCustomControl()
{
IsEnabledChanged += …
}
}
但我不喜欢每个实例中的方法注册事件处理程序。 所以我更喜欢元数据覆盖。
这有效:
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(typeof(MyCustomControl)));
IsEnabledProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(IsEnabledPropertyChanged));
}
private static void IsEnabledPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("{0}.IsEnabled = {1}", obj, e.NewValue);
}
但我不喜欢每个实例中的方法注册事件处理程序。
您不需要在每个实例中都这样做。 您可以在自定义类的构造函数中执行以下操作:
public class MyCustomControl : ContentControl
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
public MyCustomControl()
{
IsEnabledChanged += (s, e) => { /* do something */ };
}
}
另一个选择是使用DependencyPropertyDescriptor
执行任何操作以响应对现有依赖项属性的更改: https : //blog.magnusmontin.net/2014/03/31/handling-changes-to-dependency-properties/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.