只是学习WPF,无法弄清楚这种行为。例如:WPF:为什么DataTrigger删除我的默认样式?
标签从窗口一静态资源获取其初始风格。然后,我有两种方法来改变标签的样式:
- 使用一个按钮(通过代码隐藏)
- 使用复选框(通过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);
}