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 模式,我不想这样做。

4

1 回答 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>
于 2013-09-06T07:05:13.647 回答