开发者

WPF: TemplateBinding to StrokeThickness of Shape does not work?

开发者 https://www.devze.com 2022-12-12 09:35 出处:网络
Looks like the following Ellipse in ControlTemplate does not get the BorderThickness, but why? <Window.Resources>

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 开发者_如何学Pythonto work, why?


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


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.


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


You can also use the DataContext property of the Ellipse:

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

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号