Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF/Silverlight: How to DataTrigger a Storyboard Animation in MVVM?

Tags:

mvvm

wpf

xaml

I have a boolean property called IsLoginWrong, I want to then play a storyboard animation if the IsLoginWrong is true. (IsLoginWrong does an OnPropertyChanged event, so I know the binding is ok) But I'm having a hard time with the syntax. This might not even be right, but I think datatriggers can only live in Styles...

<UserControl.Style>
    <Style>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsLoginWrong}" Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard Storyboard="{StaticResource LoginWrong}"/>
                </DataTrigger.EnterActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Style>

But this throws an exception "A storyboard tree in a Style cannot specify a TargetName"... beause styles canno refer to items specifically.. awesome. so how do I do what I'm trying to do? (play animation if a boolean changes in mvvm)

Thanks

like image 930
Shai UI Avatar asked Mar 08 '11 18:03

Shai UI


2 Answers

Within a style you cannot refer to a storyboard name. So the way I got it to work is to shove your storyboard within the actual style:

<UserControl.Style>     
    <Style>         
        <Style.Triggers>             
            <DataTrigger Binding="{Binding Path=IsLoginWrong}" Value="True">                       
                <DataTrigger.EnterActions>                     
                    <BeginStoryboard>
                        <Storyboard>
                            .... PUT YOUR ACTUAL STORY BOARD IN HERE ...
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>             
            </DataTrigger>         
        </Style.Triggers>     
    </Style> 
</UserControl.Style>

Now DataTriggers can either be put into styles or control templates, so there might be a nicer way to do this with control templates. but this is what I came up with for the time being.

like image 58
Shai UI Avatar answered Sep 22 '22 02:09

Shai UI


One option would be to start the storyboard using the VisualStateManager. The article at http://blogs.infosupport.com/blogs/alexb/archive/2010/04/02/silverlight-4-using-the-visualstatemanager-for-state-animations-with-mvvm.aspx explains how to control the current state of the VisualStateManager from the view model using an attached property.

like image 40
devdigital Avatar answered Sep 20 '22 02:09

devdigital