Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to play a storyboard in MVVM?

Tags:

c#

mvvm

wpf

So, say I want to play a storyboard animation if some logic happens in the ViewModel. But the StoryBoard lives on the View, and I don't have a reference to the View from the ViewModel. How may I go and play the storyboard then?

like image 239
Shai UI Avatar asked Dec 10 '10 04:12

Shai UI


1 Answers

You can start the animation in the view using a datatrigger.

Something like this:

    ...<ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Value.Name}"  Padding="5">
                            <TextBlock.Style>
                                <Style>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Value.StartAnimation}" Value="True">
                                            <DataTrigger.EnterActions>
                                                <BeginStoryboard>
                                                    <Storyboard
                                                        Storyboard.TargetProperty="FontSize"
                                                        Duration="0:0:0.5">
                                                        <DoubleAnimation From="10" To="30" AutoReverse="True" />
                                                    </Storyboard>
                                                </BeginStoryboard>
                                            </DataTrigger.EnterActions>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBlock.Style>
                        </TextBlock>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
...
like image 73
ThomasAndersson Avatar answered Nov 05 '22 23:11

ThomasAndersson