Dot-Net

WPF:TemplateBinding 到 StrokeThickness 的 Shape 不起作用?

  • October 9, 2012

看起來 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>

TemplateBindingForeground工作得很好,橢圓是綠色的。但StrokeThickness它似乎不起作用,為什麼?

BorderThickness不是那麼容易,它是一個類型的結構Thickness(並且可以是複合的,比如BorderThickness=".0,.0,2,2"),而StrokeThicknessproperty 是類型的double

你需要IValueConverter使這個綁定工作。

另一種可能的解決方案……(因為我喜歡只使用 IValueConverters 作為最後的手段,如果你需要將它設置為其他東西,更改 Ellipse 的 DataContext 可能不起作用):

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

這等效於最初的意圖(綁定到 TemplatedParent),但使用長手標記允許您指定 Path 而不僅僅是屬性

引用自:https://stackoverflow.com/questions/1803971