【问题标题】:WPF – Custom Control – Inherited DependencyProperty and PropertyChangedCallbackWPF – 自定义控件 – 继承的 DependencyProperty 和 PropertyChangedCallback
【发布时间】: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


【解决方案1】:

这行得通:

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

【讨论】:

  • 是的,这就是我要找的,谢谢。请再问一个问题。 IsEnabledProperty 的原始行为仍然有效吗?这只会添加另一个回调,对吧?
  • 没错,但这在在线文档中也有很好的解释......
【解决方案2】:

但我不喜欢在每个实例中都使用方法注册事件处理程序。

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

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/

【讨论】:

  • 是的,我想到了这种方法。我还查看了DependencyPropertyDescriptor——但仍然——我认为对于MyCustomControl 的每个实例都添加了一些对更改事件的引用。
  • 当然。每个实例应该如何处理更改...?您认为 OverrideMetdata 对您的 CustomEnabledHandler 做了什么?
  • 我认为OverrideMetadata在实例之间“共享”了回调方法的信息,不是吗?因此回调方法需要知道DependencyObject - CustomEnabledHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)
猜你喜欢
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多