【发布时间】:2017-04-21 13:11:19
【问题描述】:
对于如下的自定义控件,如何为继承的DependencyPropertyIsEnabledProperty添加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 += …
}
}
但我不喜欢在每个实例中都使用方法注册事件处理程序。所以我更喜欢元数据覆盖。
【问题讨论】:
-
OverrideMetadata 有什么问题?但是请注意,它应该是 FrameworkPropertyMetadata 而不是 PropertyMetadata。
-
@Clemens 如果我在 XAML 中使用此控件,我会收到错误:元数据覆盖和基本元数据必须是相同类型或派生类型。 我也尝试使用
FrameworkPropertyMetadata。 -
它适用于 FrameworkPropertyMetadata。再试一次。
标签: c# wpf custom-controls