Here is a simple custom control to illustrate my issue
public sealed class TestControl : Control
{
public static DependencyProperty TestColorProperty = DependencyProperty.Register("TestColor", typeof(Brush), typeof(TestControl), new PropertyMetadata(new SolidColorBrush(Colors.Blue)));
public Brush TestColor
{
get { return (Brush)GetValue(TestColorProperty); }
set { SetValue(TestColorProperty, value); }
}
public TestControl()
{
this.DefaultStyleKey = typeof(TestControl);
}
}
As you can see, it has a single Brush dependency property, with a default value of Blue (set in the PropertyMetaData as shown above.
Here is the XAML for my control in Generic.xaml
<Style TargetType="local:TestControl">
<Setter Property="TestColor" Value="Red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TestControl">
<Border
Background="{TemplateBinding TestColor}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBlock Text="TEST" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
As you can see, I set the TestColor Brush dependency property to Red in a Style setter - overriding the default value of Blue as declared in my PropertyMetaData.
Notice that my Border in my Template uses TemplateBinding to set the background to the brush as discussed.
So what color do you think the border background gets set ? Red or Blue ?
The answer is neither.
If I set a breakpoint in my control somewhere where this value should be available (e.g. OnApplyTemplate as an example) then the value is null, rather than Red (default) as expected. In fact I have set breakpoints at all of the lifecycle points in the control and the default value in ProprtyMetaData is never used.
Setting the value within the style does nothing either (it doesn't get set to Blue as per my style setter delaration. This suggests that the style setter is failing for SolidColorBrush somehow.
However, this works
public BlankPage()
{
this.InitializeComponent();
testcont.TestColor = new SolidColorBrush(Colors.Orange);
}
and this works as well:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<local:TestControl TestColor="Green" />
</Grid>
but TemplateBinding just doesn't work, and this is important as Im trying to write re-useable custom controls.
Is this a bug ?
Dean