Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: TemplateBinding to StrokeThickness of Shape does not work?

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?

like image 794
Ciantic Avatar asked Nov 26 '09 14:11

Ciantic


4 Answers

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

like image 75
ncsu95 Avatar answered Oct 19 '22 19:10

ncsu95


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.

like image 45
Max Galkin Avatar answered Oct 19 '22 18:10

Max Galkin


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

like image 1
Ciantic Avatar answered Oct 19 '22 20:10

Ciantic


You can also use the DataContext property of the Ellipse:

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

Hope this helps!

like image 1
Horacio Nuñez Avatar answered Oct 19 '22 19:10

Horacio Nuñez