使用Style时传递值

时间:2014-05-06 08:50:42

标签: c# wpf xaml

我有一个Button样式:

<Style TargetType="{x:Type Button}" x:Key="myBtnStyle">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" 
                               x:Name="myTextBlock" />
                    <Rectangle Grid.Row="1"
                               x:Name="myRectangle" />
</ close everything>

当我将样式分配给按钮时,有没有办法将值(TextFill分别传递给myTextBlock和myRectangle)?

<Button Style="{StaticResource ResourceKey=myBtnStyle /*assign Text and Fill here?*/ }"
        Click="myBtn_Click" />

如果我无法在那里分配,那么我可以在哪里分配它?

2 个答案:

答案 0 :(得分:1)

在这里使用Button.TemplateControlTemplate)而不是Button.ContentTemplateDataTemplate)可能会更容易:

WPF: Button Template vs ContentTemplate
Difference between Control Template and DataTemplate in WPF

然后,您可以对按钮已有的属性使用TemplateBinding,例如对文字使用Button.Content,为填充使用Button.Background

<Style TargetType="{x:Type Button}" x:Key="myBtnStyle" >
    <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="Button" >
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Text="{TemplateBinding Content}" />
                    <Rectangle Grid.Row="1" Fill="{TemplateBinding Background}" />
</ close everything>

用法:

<Button Style="{StaticResource ResourceKey=myBtnStyle}"
        Content="My text here.." Background="Blue" 
        Click="myBtn_Click" />

修改
带有图像的模板,(误)使用Button.Tag

...
<ControlTemplate TargetType="Button" >
    ...
    <!--For some reason, the shorthand "{TemplateBinding Tag}" doesn't work here,
        so we must use the longer "RelativeSource" syntax in this binding:-->
    <Image Grid.Row="1" 
           Source="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                            Path=Tag}" />
    ...

用法:

<Button Style="{StaticResource ResourceKey=myBtnStyle}"
        Content="My text 1" Tag="http://programming.enthuses.me/1.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
        Content="My text 2" Tag="/MyIcons/Icon01.png" />

答案 1 :(得分:0)

如上所述,您可以使用TemplateBinding这是写作的简写:

{Binding Path=Content, RelativeSource={RelativeSource Mode=FindAncestor, 
AncestorType={x:Type Button}}}

在您的情况下,代码将是:

<TextBlock Text="{TemplateBinding Content}"  />
<Rectangle Width="50" Height="10" Fill="{TemplateBinding Button.Background}" />

用法:

<Button Style="{StaticResource ResourceKey=myBtnStyle}"
        Content="My text here.." Background="Blue" 
        Click="myBtn_Click" />