Question

I am developing a Silverlight CustomControl, that defines a dependency property named SpinnerSize. Now I want to set the width and height of a Border inside of the default template to the SpinnerSize-property using TemplateBinding:

<Style TargetType="local:MyCustomControl">
    <Setter Property="SpinnerSize" Value="12" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyCustomControl">
                <Border 
                    Width="{TemplateBinding SpinnerSize}"
                    Height="{TemplateBinding SpinnerSize}"
                    Background="Red" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The SpinnerSize reference in the above example is defined as follows:

public static readonly DependencyProperty SpinnerSizeProperty = 
    DependencyProperty.Register(
        "SpinnerSize", 
        typeof(int), 
        typeof(MyCustomControl),
        new PropertyMetadata(default(int)));

public int SpinnerSize
{
    get { return (int)this.GetValue(SpinnerSizeProperty); }
    set { this.SetValue(SpinnerSizeProperty, value); }
}

The result is that I don't see the border at all. If I set width and height of the border manually to a value everything works fine.

Is TemplateBinding a valid way to achieve that or do I have to set the width and height manually in the OnApplyTemplate()-method in the control?

Was it helpful?

Solution

Your XAML looks fine, and it is valid to use TemplateBinding like this, so the problem must be in your DependencyProperty.

Height and Width are Doubles. The Binding engine doesn't deal in implicit casts.

Change your DP to that type and it should work fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top