DependencyObject/DependencyProperty

本文介绍了WPF中依赖属性的使用方法及其重要性,依赖属性必须定义在DependencyObject对象中,WPF的多数基础类都继承自该类。此外,文章还详细解释了INotifyPropertyChanged接口的作用及其实现方式,确保数据变化时能够及时更新到UI。

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


转载于:https://my.oschina.net/u/138995/blog/184198

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值