Animating a Style property of a control using ObjectAnimationUsingKeyFrames in WPF

I am trying to animate the Style property using ObjectAnimationUsingKeyFrames. When I run the sample below, I just see a blank window, and there are no exceptions.

Almost the same pattern works in Silverlight. In WPF, it also works if I directly assign the Style property to the control. Does anyone know if it is possible to animate the Style property in WPF?

Many thanks.

<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:this="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <ResourceDictionary> <Style x:Key="TestStyle" TargetType="Control"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Canvas x:Name="Rectangle"> <Rectangle Width="200" Height="150" Fill="Red"/> </Canvas> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> </Window.Resources> <Canvas> <Canvas.Triggers> <EventTrigger RoutedEvent="Canvas.Loaded"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Target" Storyboard.TargetProperty="Style" > <DiscreteObjectKeyFrame KeyTime="0:0:0.0" Value="{StaticResource ResourceKey=TestStyle}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </Canvas.Triggers> <Canvas.Children> <ContentControl x:Name="Target"/> </Canvas.Children> </Canvas> 

+6
controls styles wpf
source share
1 answer

When ObjectAnimationUsingKeyFrames tries to animate the value obtained from DependencyObject , it tries to freeze the object first. If the object cannot be frozen, it throws an exception and the animation does not start.

If you are animating a custom type value that you wrote, it seems that you need to either deduce from Freezable or not deduce from DependencyObject .

For existing properties derived from DependencyObject , not Freezable , you cannot animate them ( StyleProperty or TemplateProperty are examples). Try using the setter property inside the style:

 <Style.Triggers> <Trigger Property="IsEnabled" Value="True"> <Setter Property="Template" Value="{StaticResource TestTemplate}"/> </Trigger> </Style.Triggers> 

Build all the transition logic in a style instead of switching between different styles. The problem you can have with this is that the target property must be a dependency property, so you cannot use IsLoaded .

I hope you find this helpful.

Last thought: you can define custom animations , although I myself did not. There is an external chance that you can write your own "ObjectAnimation", which will not be limited to Freezable or DependencyObject classes.

+1
source share

All Articles