在触发器上更改XAML中的Button内容

时间:2012-08-10 21:10:08

标签: c# wpf xaml controltemplate

我正在尝试制作一个模板,它会改变Button的背景以及它的颜色TextBlock。我在我的模板中尝试了以下XAML,但它只是使按钮在鼠标悬停时消失。有没有办法改变触发器上按钮内容的属性?

                

                <ControlTemplate TargetType="{x:Type Button}">
                <Border 
                        x:Name="Border"  
                        CornerRadius="0" 
                        BorderThickness="0"
                        Background="{x:Null}"
                        BorderBrush="#FF404040" />
                    <ControlTemplate.Triggers>
                       <Trigger Property="IsMouseOver" Value="true">
                          <Setter TargetName="Border" Property="Background" Value="White" />
                            <Setter Property="ContentTemplate">
                                <Setter.Value>
                                    <DataTemplate DataType="TextBlock">
                                        <TextBlock Foreground="Blue" />
                                    </DataTemplate>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

1 个答案:

答案 0 :(得分:2)

风格:

<Style TargetType="{x:Type Button}" x:Key="MyButton">
    <Setter Property="OverridesDefaultStyle" Value="True" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="Border"
                        CornerRadius="0"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}"
                        TextBlock.Foreground="{TemplateBinding Foreground}"
                        BorderBrush="#FF404040">
                    <ContentPresenter Margin="2"
                                      HorizontalAlignment="Center"
                                      VerticalAlignment="Center"
                                      RecognizesAccessKey="True" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="White" />
                        <Setter TargetName="Border" Property="TextBlock.Foreground" Value="Blue" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

用法:

<Button Width="100" Height="50" Content="Lalala" Style="{StaticResource MyButton}" Background="Brown" Foreground="Green" BorderThickness="2"></Button>
  1. 您错过了ContentPresenter,负责可视化Content的{​​{1}}属性。
  2. 要设置前景,您可以使用Button附加属性。
  3. Control Styles and Templates对我来说一直非常有用:)