从WPF/MVVM中的ViewModel启动动画

Ran*_*ngy 9 c# wpf mvvm

我正在编写一个MVVM应用程序并开始使用一些动画.我想在启动故事板的ViewModel上调用一些东西.这个博客有一个很有前途的方法,但实际上并没有用.IDChanged处理程序从不会因某些原因而触发.

我还发现你可以在EventTriggers上开始动画,但我不知道如何在ViewModel上引发动画.

Cow*_*bop 10

我通过使用DataTrigger并将其绑定到我的ViewModel中的属性来完成此操作.当"FlashingBackGround"属性设置为"ON"时,Storyboard动画将启动.

还要确保在项目中包含对"Microsoft.Expression.Interactions"的引用

XAML :(这直接在根节点中)

<Window
   xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
   xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
   x:Name="window" >

    ...

    <i:Interaction.Triggers>
      <ei:DataTrigger Binding="{Binding FlashingBackground, Mode=OneWay}" Value="ON">
        <ei:ControlStoryboardAction Storyboard="{StaticResource MyAnimation}"     
                                                ControlStoryboardOption="Play"/>
      </ei:DataTrigger>
    </i:Interaction.Triggers>

    ...
</Window>
Run Code Online (Sandbox Code Playgroud)

视图模型:

 private void TurnOnFlashingBackround()
    {
        FlashingBackground = "ON";
    }

    private string _FlashingBackround = "OFF";

    public string FlashingBackground
    {
        get { return _FlashingBackround; }

        private set
        {
            if (FlashingBackground == value)
            {
                return;
            }

            _FlashingBackround = value;
            this.OnPropertyChanged("FlashingBackground");
        }
    }

    public new event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
Run Code Online (Sandbox Code Playgroud)

最后,Viewmodel必须继承自"INotifyPropertyChanged"

  • 有趣的方法.但为什么不使用`boolean`而不是"ON"/"OFF"字符串? (7认同)

Ran*_*ngy 2

我最终向我的 ViewModel 添加了一个 AnimationStarted 事件,其中包含一个动画的关键字符串。然后,在视图上,我以编程方式创建动画,订阅 AnimationStarted 事件,并在动画触发时关闭相应的动画。