Routed events and dependency properties .NET wrapper confusion

前端 未结 1 1512
南笙
南笙 2021-01-25 06:22

I\'m new to WPF and have a confusion about wrapping syntax of routed events and dependency properties I\'ve seen on many sources that routed events and dependency properties are

1条回答
  •  北海茫月
    2021-01-25 06:55

    I'm gonna try to sum it up for you:

    Dependency property:

    public int MyProperty
    {
        get { return (int)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
    
    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new UIPropertyMetadata(MyDefaultValue));
    

    That's the full syntax, you don't have to memorize it, just use the "propdp" snippet in Visual Studio.
    The "get" must return a value of the type it refers to (in my example, int). Whenever you call

    int MyVar = MyProperty;
    

    The code inside "get" is evaluated.
    The set has a similar mechanism, only you have another keyword: "value" which will be the value you assign to MyVariable:

    MyProperty = 1;
    

    Will call the "set" of MyProperty and "value" will be "1".

    Now for the RoutedEvents:

    In C# (as in C++, correct me if i'm wrong), to subscribe to an event, you do

    MyProperty.MyEvent += MyEventHandler;
    

    That will call the "add" --> you're adding a handler to the stack. Now since it is not automatically garbage-collected, and we want to avoid memory leaks, we do:

    MyProperty.MyEvent -= MyEventHandler;
    

    So that our object can be safely disposed of when we don't need it anymore. That's when the "remove" expression is evaluated.

    Those mechanism allow you to do multiple things on a single "get", a widely used example in WPF would be:

    private int m_MyProperty;
    public int MyProperty
    {
       get
       {
          return m_MyProperty;
       }
       set
       {
          if(m_MyProperty != value)
          {
             m_MyProperty = value;
             RaisePropertyChanged("MyProperty");
           }
        }
    }
    

    Which, in a ViewModel that implements INotifyPropertyChanged, will notify the bindings in your View that the property has changed and need to be retrieved again (so they will call the "get")

    0 讨论(0)
提交回复
热议问题