Just learning WPF and can't figure out this behavior. Example:
The Label gets its initial style from a StaticResource on the Window. Then, I have two ways to change the style of the label:
Once I click the Button, I can no longer change the style via the CheckBox. Sorry I don't understand why this happens. Thanks in advance to anyone who can help me :-) Here is the code:
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>
CodeBehind:
private void Button_Click(object sender, RoutedEventArgs e)
{
Label1.Foreground = new SolidColorBrush(Colors.DarkOrange);
}
This is because the binding is lost on the button click. Once you directly change a value that is binding in XAML the new value removes the binding all together. You would need to have another trigger possibly and force that to happen. There is code you can write to continue the binding or re-instantiate the original binding but it's a bit of overkill. Personally I recommend staying away from the Code behind if you're going to use XAML... I myself force myself to never write code behind period but that's a design choice so it's what you choose to do.
If you have to use code behind and you do wish to stick primarily to XAML then you will need to build custom controls that use DependencyProperties etc and keep them completely generic like every other control.
That's off subject but the bottom line is you've removed the binding by clicking the button and setting the Foreground property directly. If you must use code behind and wish to keep the binding I wouldn't mind posting the code to accomplish that and you can choose to agree or not but it's a bit of a headache to design that way.