I want something to happen when the window gains focus. However, this doesn’t seem to work:
<Window x:Class="Sample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Background="Black"
Opacity="0.5">
<Grid>
</Grid>
<Window.Style>
<Style>
<Style.Triggers>
<Trigger Property="Window.IsActive" Value="true">
<Setter Property="Control.Background" Value="Blue" />
<Setter Property="Window.Title" Value="Testing" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Style>
</Window>
On the other hand, if I replace the setters with an animations on the {Enter,Exit}Actions things seem to work.
<Window x:Class="Sample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Background="Black"
Opacity="0.5">
<Grid>
</Grid>
<Window.Style>
<Style>
<Style.Triggers>
<Trigger Property="Window.IsActive" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color"
To="Blue" Duration="0:0:1" />
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Title">
<DiscreteObjectKeyFrame Value="Testing" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color"
To="Black" Duration="0:0:1" />
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Title">
<DiscreteObjectKeyFrame Value="Window1" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
</Window.Style>
</Window>
I suppose that this workaround is sufficient for my purposes, but I would like to understand why the “simple” way doesn’t work.
P.S. I can’t quite get the syntax highlighting to work completely… It seems to give up after a few levels of indention.
If you want to switch some property value with triggers based on some condition, you need to set those properties’ default value in the style itself otherwise no matter what values you set in your setter the properties’ value will always be overridden by the local values of those properties due to dependency property value precedence. In your case you need to set the value of
BackgroundandTitlein your style like this –Also, you can omit setting the value, let the trigger set for you those values. This would work too(Background and Title omitted at the time of window declaration) –