WPF has a great support for handling data: Data Binding. Unfortunately, one of the elements you bind to (the target) must have a DependencyProperty (known as the target-property).
What if you don't have a dependency property to bind to, or you just want to bind two CLR types?
For example let say that you wrote an application for simulating a car. You may have a Car and a Speedometer classes. Let say that a car handles its own speed, hence the car has its own speed state exposed by a Speed property. A speedometer measures speed, hence it also has its own speed state, thus exposes it with its own Speed property. Now you want to visualize both the Car and its Speedometer, each with its own state. So you wrote two Data Templates and you bind the data template elements with the Car.Speed and Speedometer.Speed properties.
Changing the car speed state doesn't change the speedometer speed state. You can work around this by registering to a Car.SpeedChange event, and handle it by updating the speedometer speed state. But what if you have more properties, more classes... You are right, it is a mess, unless you are using my little, simple CLR Binding class which will do the work for you.
public Car()
{
this._speedometer = new Speedometer()
{
MinSpeed = 0,
MaxSpeed = 240
};
CLRPropertyBinding binding = new CLRPropertyBinding(
this,
_speedometer,
"Speed",
CLRBindingMode.OneWayToTarget);
binding.Bind();
...
}
As you can see, instead of registering events, you only have to create an instance of the CLRPropertyBinding. This instance will do the rest.
Note that the CLRPropertyBinding class is neither completed nor perfect. It uses property descriptor (reflection) for updating both the target and the source. Also you can extend this type to support converters, error handling and so on.
Side note: this type is inspired by the WPF Binding markup extension class.
Before you download the code, read this. Also you are welcome to see more of this and other interesting Data Binding and Data Templates stuff in my session: "The Hitchhiker's Guide to WPF Data Binding", Tech-Ed Israel 2008.
You can download the complete code from here.