DependencyObject/DependencyProperty

DependencyProperty只能定義在DependencyObject對象中,WPF大多數基礎類都是這個類的子類。好比UIElement.在WPF中定義的目標屬性必須是依賴屬性。 this

同時咱們常常會更新座位源的底層數據,而後更新到界面,這是被綁源必須實現INotifyPropertyChanged接口。 spa

當源數據更新時若是想更新界面須要觸發PropertyChanged事件, code

WPF will subscribe to the PropertyChanged event when you bind to your object. This is the core way that databinding works. component

It actually does this via the PropertyChangedEventManager using the WeakEvent pattern in WPF. orm

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));
  }

接口

本站公眾號
   歡迎關注本站公眾號,獲取更多信息