2017-04-21 97 views
1

自定义控件像下面这样的情况下,如何添加PropertyChangedCallback为继承的DependencyProperty IsEnabledPropertyWPF - 自定义控制 - 继承的DependencyProperty和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

OverrideMetadata有什么问题?但请注意,它应该是FrameworkPropertyMetadata而不是PropertyMetadata。 – Clemens

+0

@Clemens如果我在** XAML **中使用这个控件,我会收到错误:_Metadata覆盖和基础元数据必须是相同类型或派生类型._我也使用'FrameworkPropertyMetadata'尝试它。 – David

+0

它适用于FrameworkPropertyMetadata。再试一次。 – Clemens

回答

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); 
} 
+0

是的,这是我一直在寻找的,谢谢。还有一个问题。 “IsEnabledProperty”的原始行为仍然有效?这只会增加一个回调,对吧? – David

+0

的确如此,但在线文档中也有详细说明。 – Clemens

1

But I don't like the approach register event handler in every instance.

您不需要在每个实例中都这样做。你可以做你的自定义类的构造函数:

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/

+0

是的,我认为这种方法。我也看着'DependencyPropertyDescriptor' - 但仍然 - 我认为每个'MyCustomControl'实例都增加了一些对change事件的引用。 – David

+0

当然。每个实例应该如何处理变更......?你认为OverrideMetdata对你的CustomEnabledHandler有什么作用? – mm8

+0

我认为'OverrideMetadata'“共享”实例间回调方法的信息,不是吗?因此,回调方法需要知道'DependencyObject' - 'CustomEnabledHandler(DependencyObject d,DependencyPropertyChangedEventArgs e)'。 – David