WPF - custom types and polymorphism
I was working on a WPF application and needed to do a complex rectangle-like UI element. Hey custom styles is what WPF is good at right? To be quite exact I needed a custom control template, since I couldn't style a rectangle the way I wanted to.
I decided to use a System.Windows.Control (which isn't sealed, a rectangle is) and inherit from this in order to add some custom behavior. I created a custom template by creating a control template element inside my Window.Resources section like this:
<ControlTemplate x:Key="ControlTemplate" TargetType="{x:Type Control}">...</ControlTemplate>
This works just fine as long as long as your custom class acts like a control. The moment you try to bind to a custom dependancy property like this (in which Title is our custom dependancy property):
<TextBlock Text="{TemplateBinding Property=Title}" />
You get the error message "Cannot convert the string 'Title' into an object of type 'System.Windows.DependencyProperty'. The result is 'null', which is not an allowable value.."
This actually is completely logical since you told the control template that you would be feeding it a System.Windows.Control but instead you are feeding it your own custom type which inherits from System.Windows.Control.
The right way to do this is to reference your type using the clr-namspace mapping syntax and changing your control template decleration like the following:
<ControlTemplate x:Key="ControlTemplate" TargetType="{x:Type YourCustomControl}">...</ControlTemplate>
Although this sounds logical it did keep me busy a while. Perhaps the WPF folks want to do some less-cryptic error message on this one.
Hope this helps out somebody.