Routed events and dependency properties .NET wrapp

2020-04-27 05:01发布

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 wrapped like this

// Routed Event
public event RoutedEventHandler Click
{
 add
 {
  base.AddHandler(ButtonBase.ClickEvent, value);
 }
 remove
 {
  base.RemoveHandler(ButtonBase.ClickEvent, value);
 }
}

// Dependency Property
public Thickness Margin
{
 set { SetValue(MarginProperty, value); }
 get { return (Thickness)GetValue(MarginProperty); }
}

I have never seen add / remove / set / get sort of keywords in C#. Are these are part of C# language as Keywords and i never experienced or worked with them because i didn't worked in C# as pro i'm a C++ programmer? If not keywords then how they are handled by compiler if they are not part of C# and how they are working

1条回答
神经病院院长
2楼-- · 2020-04-27 05:22

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")

查看更多
登录 后发表回答