对于自定义控件,如下所示,如何为继承的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 += …
}
}
但我不喜欢每个实例中的方法注册事件处理程序。所以我更喜欢元数据重写。
答案 0 :(得分:2)
这有效:
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);
}
答案 1 :(得分:1)
但我不喜欢每个实例中的方法注册事件处理程序。
您不需要在每个实例中都这样做。您可以在自定义类的构造函数中执行:
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/