使用WPF MVVM运行动画

时间:2013-09-06 06:18:21

标签: wpf animation mvvm

使用MVVM时在WPF中运行动画有哪些选项(避免代码隐藏)?

我在XAML资源中定义了我的动画:

<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>

我希望在单击按钮时在某些UI元素上运行上述动画。该按钮具有命令绑定:

<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

到目前为止,我已经从代码隐藏运行动画:

Dim stb As Storyboard = TryCast(FindResource("showMe"), Storyboard)
stb.Begin(imgSomeImage)

...但是这需要我处理代码隐藏中的按钮单击事件,由于MVVM模式,我不想这样做。

1 个答案:

答案 0 :(得分:2)

如何在按钮点击事件中触发故事板内的动画:

<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>