DependencyProperty只能定义在DependencyObject对象中,WPF大多数基础类都是这个类的子类。比如UIElement.在WPF中定义的目标属性必须是依赖属性。
同时我们经常会更新座位源的底层数据,然后更新到界面,这是被绑源必须实现INotifyPropertyChanged接口。
当源数据更新时如果想更新界面需要触发PropertyChanged事件,
WPF will subscribe to the PropertyChanged event when you bind to your object. This is the core way that databinding works.
It actually does this via the PropertyChangedEventManager using the WeakEvent pattern in WPF.
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, which a property value has changed. The INotifyPropertyChanged interface contains an event called PropertyChanged. Whenever a property on a ViewModel / Model object has a new value, it can raise the PropertyChanged event to notify the WPF binding system of the new value. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value。
If you just did
PropertyChanged(this, new PropertyChangedEventArgs(name))
you would get a NullRefrerenceException if no one was subscribed to the event PropertyChanged. To counteract this you add a null check
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name))
}
Now, if you are using multi-threading someone could unscribe between the null check and the calling of the event, so you could still get a NullRefrerenceException. To handle that we copy the event handler to a temporary variable
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
Now if someone unsubscribes from the event our temporary variable handler will still point to the old function and this code now has no way of throwing a NullRefrerenceException.
Most often you will see people use the keyword var instead, this makes it so you don't need to type in the full type of the temporary variable, this is the form you will see most often in code.
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
来源:oschina
链接:https://my.oschina.net/u/138995/blog/184198