WPF: TemplateBinding to StrokeThickness of Shape does not work?

3.4k views Asked by At

Looks like the following Ellipse in ControlTemplate does not get the BorderThickness, but why?

<Window.Resources>
    <ControlTemplate x:Key="EllipseControlTemplate" TargetType="{x:Type TextBox}">
        <Grid>
            <Ellipse 
                Width="{TemplateBinding ActualWidth}" 
                Height="{TemplateBinding ActualHeight}" 
                Stroke="{TemplateBinding Foreground}" 
                StrokeThickness="{TemplateBinding BorderThickness}" />
                <ScrollViewer Margin="0" x:Name="PART_ContentHost" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <TextBox
        Template="{DynamicResource EllipseControlTemplate}" 
        Foreground="Green"
        BorderThickness="15" />
</Grid>

TemplateBinding to Foreground works just fine, the ellipse is green. But to StrokeThickness it doesn't seem to work, why?

4

There are 4 answers

3
Massimiliano On BEST ANSWER

BorderThickness is not that easy, it is a struct of type Thickness (and can be composite, like BorderThickness=".0,.0,2,2"), while StrokeThickness property is of type double.

You need IValueConverter to make this binding work.

0
Ciantic On

There was naming gotcha: BorderThickness is type of Thickness, and StrokeThickness is type of double. So we need IValueConverter.

1
ncsu95 On

Another possible solution ... (because i like to only use IValueConverters as a last resort, and changing the DataContext of the Ellipse might not work if you need it to be set to something else):

<Ellipse StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BorderThickness.Top}" />

This is equivalent to the original intent (to bind to the TemplatedParent), but using the long-hand markup allows you to specify a Path rather than just a property

0
Horacio Nuñez On

You can also use the DataContext property of the Ellipse:

<Ellipse DataContext="{TemplateBinding BorderThickness}" StrokeThickness="{Binding Top}" />

Hope this helps!