【发布时间】:2017-06-13 21:44:06
【问题描述】:
刚刚学习 WPF,无法弄清楚这种行为。示例:
标签从窗口上的静态资源中获取其初始样式。那么,我有两种方法可以改变标签的样式:
- 使用按钮(通过 CodeBehind)
- 使用复选框(通过 DataTrigger 绑定)。
单击按钮后,我无法再通过 CheckBox 更改样式。 抱歉,我不明白为什么会这样。提前感谢任何可以帮助我的人:-) 这是代码:
XAML:
<Window x:Class="WtfDataTrigger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WtfDataTrigger"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="Label" x:Key="LabelStyle">
<Setter Property="Foreground" Value="Red" />
</Style>
</Window.Resources>
<StackPanel>
<Label Name="Label1" Content="Label1" FontSize="24">
<Label.Style>
<Style TargetType="Label" BasedOn="{StaticResource LabelStyle}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=Checkbox, Path=IsChecked}" Value="True">
<Setter Property="Foreground" Value="Aqua" />
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label >
<Button Content="Click Me to Change Label Style Using Routed Events" FontSize="18" Click="Button_Click" />
<CheckBox Name="Checkbox" Content="Check Me to Change Label Style Using Data Trigger" FontSize="18">
</CheckBox>
</StackPanel>
</Window>
代码隐藏:
private void Button_Click(object sender, RoutedEventArgs e)
{
Label1.Foreground = new SolidColorBrush(Colors.DarkOrange);
}
【问题讨论】:
标签: xaml styles overriding datatrigger