In the previous Post, I described a bunch of theoretical knowledge about Data Binding in WPF. Now, we will further analyze some of these aspects through instances.
When introducing the types of WPF Data Binding sources, the first type is any CLR object. It should be noted that, although WPF supports any CLR object, it does not work for a common CLR object class. We also need to implement a change notification mechanism on the CLR object class.
WPF encapsulates this notification mechanism in the INotifyPropertyChanged interface. As long as our CLR object class implements this interface, it has the ability to notify the customer, usually the target of notifying the binding after the property changes.
The following is a simple example to implement a Camera class that supports the notification function:
Using System;
Using System. ComponentModel;
Using System. Windows. Media. Media3D;
Namespace LYLTEST
{
Public class Camera: INotifyPropertyChanged
{
Private PerspectiveCamera m_Camera;
Public event PropertyChangedEventHandler PropertyChanged;
Public Camera ()
{
M_Camera = new PerspectiveCamera ();
}
Private void policypropertychanged (String info)
{
If (PropertyChanged! = Null)
{
PropertyChanged (this, new PropertyChangedEventArgs (info ));
}
}
Public PerspectiveCamera CameraProp
{
Get {return m_Camera ;}
Set
{
If (value! = M_Camera)
{
This. m_Camera = value;
NotifyPropertyChanged ("CameraProp ");
}
}
}
}
}
This code is very simple. First, introduce the namespace required by INotifyPropertyChanged and PerspectiveCamera used in the class. The difference between this and common CLR classes is that there is a public PropertyChangedEventHandler event type. Then, we wrap CameraProp in the. NET property to determine whether the property has changed. If yes, call another private function policypropertychanged using the current attribute name string "CameraProp. It constructs a PropertyChangedEventArgs object based on the attribute name and calls PropertyChanged. It is a notification event that should be called when attributes change.
Finally, if we need to notify that all attributes have changed, replace the preceding attribute string "CameraProp" with the parameter NULL.