简单的问题,真的。我有以下按钮定义了一些简单的绑定&样式触发器:
<Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Transparent" BorderThickness="0" Command="{Binding AcceptValueInputCommand}">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding ValueInputEnabled}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding IsPredefined}" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="Black" />
</DataTrigger>
</Style.Triggers>
<Setter Property="Visibility" Value="Visible"/>
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
</Style>
</Button.Style>
<Viewbox>
<TextBlock Text="{Binding Value}" />
</Viewbox>
</Button>
我遇到的问题是我的触发器是&#34; IsPredefined&#34;没有将按钮的背景设置为红色。前景 正确设置为黑色(虽然我不知道为什么它没有从风格之外的设置者中选择它)。我认为这个问题与按钮上的命令绑定有关,因为如果我注释掉绑定,那么按钮突然变红了! (注意,在&#34; IsPredefined&#34;评估为true的所有情况下,命令的CanExecute()应该评估为false)。有什么想法吗?
(编辑为将黑色前景添加到IsPredefined触发器中)。
答案 0 :(得分:1)
这是因为当CanExecute返回false时,按钮将被禁用,并且样式触发器将被按钮的默认控制模板中定义的控件模板触发器覆盖,该模板将背景设置为灰色。
如果你想要改变它,你必须覆盖按钮的默认模板,并摆脱负责将其设置为灰色的触发器。这个样本应该有效:
<Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Transparent" BorderThickness="0" Command="{Binding AcceptValueInputCommand}">
<Button.Template>
<ControlTemplate TargetType="ButtonBase">
<Border BorderThickness="{TemplateBinding Border.BorderThickness}"
BorderBrush="{TemplateBinding Border.BorderBrush}"
Background="{TemplateBinding Panel.Background}"
Name="border"
SnapsToDevicePixels="True">
<ContentPresenter RecognizesAccessKey="True"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
Name="contentPresenter"
Margin="{TemplateBinding Control.Padding}"
HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"
Focusable="False" />
</Border>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnable}" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="Black" />
</DataTrigger>
</Style.Triggers>
<Setter Property="Visibility" Value="Visible"/>
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
</Style>
</Button.Style>
<Viewbox>
<TextBlock Text="{Binding Value}" />
</Viewbox>
</Button>