WPF覆盖setter属性

时间:2010-01-12 17:04:55

标签: wpf styles controltemplate setter

我在XAML中使用了一个标签样式:

<Style x:Key="TreatEye" TargetType="Label">
        <Setter Property="Foreground" Value="#d1d1d1" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="30" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Label">
                    <Canvas>                            
                        <TextBlock x:Name="retreatText" Canvas.Left="80" Canvas.Top="5" FontSize="16"  Text="Retreatment"/>                                                        
                        <TextBlock x:Name="bioinsulatorText" Canvas.Left="21" Canvas.Top="33" Text="Bioinsulator" />
                        <TextBlock x:Name="kxlText" Canvas.Left="21" Canvas.Top="70" Text="KXL Kit" />
                    </Canvas>
...

我看到的问题是“reatreatText”的FontSize属性没有从setter值30覆盖。这样构建正常,但是结束显示的“reatreatText”大小为30.为什么不覆盖此值?

提前致谢。

2 个答案:

答案 0 :(得分:3)

抱歉,我在Kaxaml中尝试了您的代码并按预期工作:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
  <Style x:Key="TreatEye" TargetType="Label">
        <Setter Property="Foreground" Value="#d1d1d1" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="30" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Label">
                    <Canvas>                            
                        <TextBlock x:Name="retreatText" Canvas.Left="80" Canvas.Top="5" FontSize="16" Text="Retreatment"/>                                                        
                        <TextBlock x:Name="bioinsulatorText" Canvas.Left="21" Canvas.Top="33" Text="Bioinsulator" />
                        <TextBlock x:Name="kxlText" Canvas.Left="21" Canvas.Top="70" Text="KXL Kit" />
                    </Canvas>
                </ControlTemplate>
        </Setter.Value>                
      </Setter>
     </Style>
    </Page.Resources>

  <Grid>  
    <Label Style="{StaticResource TreatEye}">Ejemplo</Label>
  </Grid>
</Page>

结果:

alt text http://img231.imageshack.us/img231/695/capture2p.png

答案 1 :(得分:0)

您需要在TextBlock上设置TemplateBinding。

<TextBlock x:Name="retreatText"
           Canvas.Left="80" 
           Canvas.Top="5" 
           FontSize="{TemplateBinding FontSize}" 
           Text="Retreatment"/> 

这就是setter属性如何传播到内部结构。