TemplateBinding error

577 views Asked by At

I develop a custom control which has a dependency property

public static readonly DependencyProperty StateBorderBrushProperty =
        DependencyProperty.Register("StateBorderBrush", typeof(Brush), typeof(SmartCanvas),
        new FrameworkPropertyMetadata(Brushes.Transparent,
            FrameworkPropertyMetadataOptions.None));

The problem arise when I try to set ControlTemplate of my control from outside xaml like

<ControlTemplate TargetType="controls:SmartPrimitive">
                    <Grid>
                        <ContentPresenter/>
                        <Border BorderBrush="{TemplateBinding StateBorderBrush}" BorderThickness="2"/>
                    </Grid>
                </ControlTemplate>

It sounds like "XamlParseException: The given key was not present in the dictionary" in the string with TemplateBinding above. What could be wrong?

3

There are 3 answers

2
Serge P. On BEST ANSWER

I've just misspelled with the type of the DependencyProperty owner. It should be SmartPrimitive, not SmartCanvas. But... WPF exception might be more informative.

0
ndonohoe On

You missed out the {x:Type } declaration

<ControlTemplate TargetType="{x:Type controls:SmartPrimitive}">
     <Grid>
         <ContentPresenter/>
         <Border BorderBrush="{TemplateBinding StateBorderBrush}" BorderThickness="2"/>
     </Grid>
</ControlTemplate>

This means that you are supplying a string to the TargetType instead of a Type

The x:Type markup extension supplies a from-string conversion behavior for properties that take the type Type. The input is a XAML type.

http://msdn.microsoft.com/en-us/library/ms753322%28v=vs.110%29.aspx

0
CongoTM On

I had a similar problem in a similar case. So I searched it and found that it cannot be TemplateBinding in this case.

Like Sivasubramanian's answer and explanation here -> Using a TemplateBinding in ControlTemplate.Triggers

In TemplateBinding : Have a close look at this, The resolved value of the Max:MyControl.Bar is going to act as the resource key for the Template binding [Here the value of Bar is not an actual value, instead it s a property key name ] which doesnt exists and so it throws the error "The given key was not present in the dictionary."

So basically, changing TemplateBinding to a Binding

<ControlTemplate TargetType="{x:Type controls:SmartCanvas}">
 <Grid>
     <ContentPresenter/>
     <Border BorderBrush="{Binding StateBorderBrush, UpdateSourceTrigger=PropertyChanged}" BorderThickness="2"/>
 </Grid>