路由事件和依赖项属性.NET包装器混淆
我是WPF的新手,并且对于路由事件和依赖属性的语法包含了一些困惑,我在许多来源上看到路由事件和依赖属性被包装成这样
// 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); } }
我从未在C#中看到添加/删除/设置/获取关键字的类型。 这些是C#语言的一部分作为关键字,我从来没有经历过或使用它们,因为我没有在C#中工作,因为我是一名C ++程序员? 如果不是关键字,那么如果它们不是C#的一部分以及它们如何工作,它们如何被编译器处理
我会试着总结一下你:
依赖属性:
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));
这是完整的语法,您不必记住它,只需使用Visual Studio中的“propdp”代码段即可。
“get”必须返回它引用的类型的值(在我的示例中为int)。 无论何时打电话
int MyVar = MyProperty;
评估“get”中的代码。
该集合具有类似的机制,只有您有另一个关键字:“value”,它将是您分配给MyVariable的值:
MyProperty = 1;
将调用MyProperty的“set”,“value”将为“1”。
现在为RoutedEvents:
在C#中(如在C ++中,如果我错了,请纠正我),订阅一个事件,你做到了
MyProperty.MyEvent += MyEventHandler;
这将调用“添加” – >您正在向堆栈添加处理程序。 既然它不是自动垃圾收集,我们想避免内存泄漏,我们做:
MyProperty.MyEvent -= MyEventHandler;
因此,当我们不再需要它时,我们的对象可以安全地处理掉。 那就是评估“删除”表达式的时候。
这些机制允许你在一个“get”上做多个事情,WPF中一个广泛使用的例子是:
private int m_MyProperty; public int MyProperty { get { return m_MyProperty; } set { if(m_MyProperty != value) { m_MyProperty = value; RaisePropertyChanged("MyProperty"); } } }
其中,在实现INotifyPropertyChanged的ViewModel中,将通知View中的绑定,该属性已更改,需要再次检索(因此他们将调用“get”)