【问题标题】:WPF: TemplateBinding to StrokeThickness of Shape does not work?WPF:TemplateBinding 到 StrokeThickness 的 Shape 不起作用?
【发布时间】:2010-12-20 17:04:20
【问题描述】:

看起来 ControlTemplate 中的以下 Ellipse 没有得到 BorderThickness,但为什么呢?

<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>

模板绑​​定到Foreground 工作得很好,椭圆是绿色的。但是对于StrokeThickness 似乎不起作用,为什么?

【问题讨论】:

    标签: .net wpf xaml .net-3.5 templatebinding


    【解决方案1】:

    BorderThickness 不是那么容易,它是一个Thickness 类型的结构(并且可以是复合的,如BorderThickness=".0,.0,2,2"),而StrokeThickness 属性的类型是double

    您需要IValueConverter 才能进行此绑定。

    【讨论】:

    • 抱歉,我自己已经找到了答案。看看我写的答案......你可能是这个意思。
    • 对你有好处 :) 不过,我的更早 :)
    • 这是真的!如果你提到类型差异,我会选择你的作为解决方案,这是关键。
    【解决方案2】:

    存在命名问题:BorderThicknessThickness 的类型,StrokeThicknessdouble 的类型。所以我们需要IValueConverter

    【讨论】:

      【解决方案3】:

      您还可以使用 Ellipse 的 DataContext 属性:

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

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        另一种可能的解决方案...(因为我喜欢只使用 IValueConverters 作为最后的手段,如果您需要将 Ellipse 的 DataContext 设置为其他值,则可能无法更改):

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

        这相当于最初的意图(绑定到 TemplatedParent),但使用长手标记允许您指定路径而不仅仅是属性

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 2017-11-01
        相关资源
        最近更新 更多