您的位置:首页 > 移动开发 > Objective-C

DependencyObject/DependencyProperty

2013-12-13 00:00 281 查看
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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息