我在使用 datatrigger 更改Button的背景颜色时遇到了一些问题但是没有发生。
我的代码就是这个
<Window x:Class="DataBinding.DataTrigger2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DataTrigger2" Height="300" Width="300">
<Button Height="50" Name="btn">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Control.Background" Value="YellowGreen"></Setter>
<Setter Property="Control.Foreground" Value="Brown"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=btn, Path=IsPressed}" Value="True">
<Setter Property="Control.Background" Value="Purple"></Setter>
<Setter Property="Control.Foreground" Value="Red"></Setter>
<Setter Property="Control.FontSize" Value="20"></Setter>
<Setter Property="Control.FontWeight" Value="Light"></Setter>
<Setter Property="Control.Width" Value="150"></Setter>
<Setter Property="Control.Height" Value="50"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<Button.Content>
The Gaming World Inc.
</Button.Content>
</Button>
答案 0 :(得分:1)
单击鼠标时看不到Button.Background
颜色变化的原因是因为默认ControlTemplate
定义了它在不同状态下应该是什么样子,例如。按下,禁用。这些是在VisualStateManager.VisualStateGroups
的{{1}}部分中定义的,它们可能会覆盖您的ControlTemplate
更改。
作为简单的证据,我们可以为Background
提供基本的ControlTemplate
,但不会显示Button
部分,然后您会看到VisualStateManager.VisualStateGroups
颜色变化。试试这个:
Background
您可以在MSDN上的Button Styles and Templates页面中找到<Button Height="50" Name="btn">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Control.Background" Value="YellowGreen"></Setter>
<Setter Property="Control.Foreground" Value="Brown"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=btn, Path=IsPressed}" Value="True">
<Setter Property="Control.Background" Value="Purple"></Setter>
<Setter Property="Control.Foreground" Value="Red"></Setter>
<Setter Property="Control.FontSize" Value="20"></Setter>
<Setter Property="Control.FontWeight" Value="Light"></Setter>
<Setter Property="Control.Width" Value="150"></Setter>
<Setter Property="Control.Height" Value="50"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<Button.Content>
The Gaming World Inc.
</Button.Content>
</Button>
控件的原始/默认ControlTemplate
...您可能希望将Button
的更多内容复制到你的ControlTemplate
看起来更像原始的。{/ p>