1

我正在尝试制作一个模板来改变 aButton的背景以及它的颜色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>
4

1 回答 1

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,负责可视ContentButton.
  2. 要设置前景,您可以使用TextBlock.Foreground附加属性。
  3. 控制样式和模板对我来说一直非常有用:)
于 2012-08-11T04:41:32.980 回答