ColorAnimation starts only if a color is set
On the startup window, a grid with a TextBlock is defined, like follows:
<Grid>
<TextBlock Text="stackoverflow.com"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="Yellow">
<TextBlock.Triggers>
<EventTrigger RoutedEvent="TextBlock.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="200"
Duration="0:0:5"
Storyboard.TargetProperty="(TextBlock.FontSize)" />
<ColorAnimation To="Blue"
Duration="0:0:5"
Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</TextBlock.Triggers>
</TextBlock>
</Grid>
Within the TextBlock, a simple DoubleAnimation and a ColorAnimation is defined, so nothing spectacular. After pressing F5 in VS, the animation starts directly.
A strange behavior appears after removing Foreground="Yellow"
. By default, the Foreground of a TextBlock is set to black (depending on the preferred system theme). Now both animations should start and the colors should go from black to blue. That isn’t so, the animation won’t start. Also by setting in the ColorAnimation the From
property to black, the animation doesn’t start.
Why does this behavior appear and what is the reason? From my point of view, I cannot see a logical reason whether its matter to set a color or not.
Edit (additional information)
An exception won’t thrown whether the Foreground property is set or not. The funny thing is now that if the Foreground property is not set, the default color will be chosen. You can simply verify it by writing following: Debug.WriteLine(this.textBlock.Foreground.ToString());
(Name of the TextBlock additionally added). The color gets resolved by the system. Also by changing the Windows Theme, the color gets resolved. So, the color is implicitly set to the TextBlock. Should be work, right?
Writing Foreground="Back"
doesn't match to the current selected Windows theme. Instead of doing this, I would prefer a DynamicResource a开发者_开发问答s follows
Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"
The StaticResource works fine whereas the DynamicResource won’t work, so the animation doesn’t start.
First, WPF knows the implicit color. Second, the DynamicResource won’t for any reason work. Why? Possible bug?
If the value is not set an exception is thrown, you cannot animate the default foreground because the instance is immutable. (If you trigger the animation using the loaded event like this it will just be swallowed.)
精彩评论