ControlTemplates are one of the more powerful features of WPF as far as I know. They let you design custom made controls and to control their behaviour, all from XAML. That is very handy. Let’s say for example that you have a checkbox and another control beside it and the checked event enables or disables that control. Programmatically you can access the controls in the template using the FindName method wich is very handy.
I’ve written a sample code for that and put it together with another sample from the internet to make it more complete. There are quite a few documentation on ControlTemplates over the network.
Now I’d like to show you some issues I’ve faced, some of them are fixed and some of them still issues because of the behaviour of WPF. Again and again the problem for me is that the XAML is not very well connected to the C# API.
In the Zip file you can find the DateControl which is a custom control to set and get dates. It has a DependencyProperty intended to be used from XAML and also a standard property intented to be used from C#. Well, the Get works fine but the if you Set the property through XAML and after that you try to Set the property through C#, it doesn’t change. See the line 61 at DateControl.cs.
The other issue with the DateControl is that I’m populating the ItemsSource property on the dropdowns in the XAML which is displayed succesfully but when I try to access the property in C# it turns out that it’s null. See the PopulateGui method at DateControl.cs
The last curious thing is the way WPF builds the controls. In the constructor of the class all the children (controls) of the current control are surprisingly null and they become avaiable after the constructor finishes. That could be understable but what is not very understable is that the construction process throw events :-). You can see have a look at the Checked method at Window1.xaml.cs. The checkbox has the Checked event associated and its IsChecked property is set to true in the XAML so the event is fired at construction time and you have to add special treatment in the event handler to avoid NullReference exceptions. It makes no much sense to me.
Here you go the Zip File: ControlTemplatesTest1.zip