使用WPF MVVM运行动画

3

当使用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个回答

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>

从代码后台处理动画,同时从ViewModel处理业务逻辑?这是否意味着需要定义按钮的点击事件处理程序和命令绑定? - Nuts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接