代码之家  ›  专栏  ›  技术社区  ›  devuxer

我的WPF样式设置器可以使用TemplateBinding吗?

  •  25
  • devuxer  · 技术社区  · 16 年前

    <Style
        x:Key="MyBorderStyle"
        TargetType="Border">
        <Setter
            Property="Padding"
            Value="{TemplateBinding Padding}" />
    </Style>
    

    “Padding”成员无效,因为它没有限定类型名称。

    注意:我尝试这样做的原因是,我想在一系列类似的ControlTemplates中包含相同的边框。

    <Setter
        Property="Padding"
        Value="{TemplateBinding GridViewColumnHeader.Padding}" />
    

    …它确实编译了,但当我运行这个应用程序时,我得到了一个 XamlParseException :

    无法将属性“value”中的值转换为“”类型的对象。

    我想也许有资格 Padding 随着 GridViewColumnHeader (这是我想使用这种风格的ControlTemplate)可以工作,但没有骰子。

    编辑:

    好吧,根据文件 TemplateBinding ,它说:

    所以听起来我想做的事情简直是不可能的。我真的很想为我的控件模板中的某些控件创建可重用的样式,但我想模板绑定不能包含在这些样式中。

    3 回复  |  直到 3 年前
        1
  •  34
  •   Shane Arney    15 年前

    TemplateBinding

    MSDN documentation :

    但无论出于什么原因,具体说明 TemplatedParent

    <StackPanel>
        <StackPanel.Resources>
            <ControlTemplate x:Key="BarButton" TargetType="{x:Type Button}">
                <ControlTemplate.Resources>
                    <Style TargetType="TextBlock" x:Key="ButtonLabel">
                        <Setter Property="Text" Value="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type Button}} }" />
                    </Style>
                </ControlTemplate.Resources>
                <Grid>
                    <!-- Other controls here -->
                    <TextBlock Name="LabelText" Style="{StaticResource ButtonLabel}" />
                </Grid>
            </ControlTemplate>
        </StackPanel.Resources>
        <Button Width="100" Content="Label Text Here" Template="{StaticResource BarButton}" />
    </StackPanel>
    
        2
  •  3
  •   Tim Cooper    14 年前

    {TemplateBinding ...} 快捷方式在Setter中不可用。

    Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Padding}" .