Reputation: 2813
What are the options to run an animation in WPF when MVVM is used (and code-behind avoided)?
I have defined my animation in XAML Resources:
<Storyboard x:Key="showMe">
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}" />
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0.5" From="0" To="1" />
</Storyboard>
I want to run the above animation on some UI element when a button is clicked. The button has a command binding:
<Button Name="btnShowImage" Command="{Binding SomeCommand}" />
MVVM:
Public Property SomeCommand As ICommand
Get
If _SomeCommand Is Nothing Then _SomeCommand = New RelayCommand(New Action(AddressOf DoSomething))
Return _SomeCommand
End Get
Set(value As ICommand)
_SomeCommand = value
End Set
End Property
Private _SomeCommand As ICommand
Private Sub DoSomething
'no access to View from here so how to run the animation?
End Sub
Up to this point I have run the animation from code-behind:
Dim stb As Storyboard = TryCast(FindResource("showMe"), Storyboard)
stb.Begin(imgSomeImage)
...but that requires I handle the button click event in code-behind which I do not want to do due to MVVM pattern.
Upvotes: 3
Views: 1458
Reputation: 1475
How about triggering the animation inside a storyboard within the button clicked event:
<Button>
OK
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard x:Key="showMe">
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}" />
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0.5" From="0" To="1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
Upvotes: 2