How To Raise Property Changed events on a Dependency Property?

后端 未结 5 1864
长情又很酷
长情又很酷 2020-11-30 20:59

I have a control with two properties. One is a DependencyProperty, the other is an \"alias\" to the first one. How do I raise the PropertyChanged

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 21:50

    1. Implement INotifyPropertyChanged in your class.

    2. Specify a callback in the property metadata when you register the dependency property.

    3. In the callback, raise the PropertyChanged event.

    Adding the callback:

    public static DependencyProperty FirstProperty = DependencyProperty.Register(
      "First", 
      typeof(string), 
      typeof(MyType),
      new FrameworkPropertyMetadata(
         false, 
         new PropertyChangedCallback(OnFirstPropertyChanged)));
    

    Raising PropertyChanged in the callback:

    private static void OnFirstPropertyChanged(
       DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
       PropertyChangedEventHandler h = PropertyChanged;
       if (h != null)
       {
          h(sender, new PropertyChangedEventArgs("Second"));
       }
    }
    

提交回复
热议问题