Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM Property Change Animation

I am looking for a clean way to start an animation that will have dynamic values. Basically I want to do an animation where an element changes width based on the data of another element. Say I have a TextBlock that's Text Property is Binding. When this property changes I want a visual element say a Rectangle for our sake to do a DoubleAnimation changing the width from previous value to the new value.

I am trying to stay away from putting code in my view if possible. I've looked into DataTriggers but they seem to require that you know what the value would be such as an Enum. In my case it is just the value changing that needs to trigger a storyboard and the animation would need to start at the current(previous) value and move nicely to the new value.

Any ideas. Maybe I just missed a property.

like image 406
cjibo Avatar asked Oct 30 '09 13:10

cjibo


2 Answers

Here is the solution I ended up with. To do the Animation based on data in my ViewModel I used a DataTrigger. Below is my Style for the control.

<Style TargetType="Grid" x:Key="DetailRotation" >
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=AnimationState}" Value="New">
            <DataTrigger.EnterActions>
                <StopStoryboard BeginStoryboardName="EndAnimation" />
                <BeginStoryboard Name="NewAnimation">
                    <Storyboard>
                        <ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,30,0,0" To="0,0,0,0" Duration="0:0:1" />
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:1" />
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
            <DataTrigger.ExitActions>

            </DataTrigger.ExitActions>

        </DataTrigger>
        <DataTrigger Binding="{Binding Path=AnimationState}" Value="End">
            <DataTrigger.EnterActions>
                <StopStoryboard BeginStoryboardName="NewAnimation" />
                <BeginStoryboard Name="EndAnimation">
                    <Storyboard>
                        <ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,0,0,0" To="0,-20,0,0" Duration="0:0:1"/>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:1" />
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
        </DataTrigger>

    </Style.Triggers>
</Style>
like image 52
cjibo Avatar answered Oct 05 '22 12:10

cjibo


You could explore using Attached Properties to hook up the necessary logic to the Storyboard/Animation that you desire.

This won't necessarily stop you from having to write code, but it will keep it separated from the view and allow it to be re-used across multiple views.

like image 21
Richard McGuire Avatar answered Oct 05 '22 13:10

Richard McGuire