简体   繁体   English

从视图模型(WPF)在视图中调用动画

[英]Calling animations in a view from a viewmodel (WPF)

What I have: A style resource which contains animation definitions and a view definition, a viewmodel which contains Data, Properties and ICommands. 我所拥有的:一种样式资源,其中包含动画定义和视图定义,一个视图模型中包含数据,属性和ICommands。

Currently the application can call VM functions via Button Clicks (using ICommand), View with binding to VM Properties & it is able to run animations from a button.click event trigger. 当前,该应用程序可以通过“按钮单击”(使用ICommand),具有绑定到“ VM属性”的“视图”来调用VM函数,并且能够从button.click事件触发器运行动画。

What I am looking to do; 我要做什么; If a style is applied to a listbox(for example) How do I trigger animations from the VM directly? 如果将样式应用于列表框(例如),如何直接从VM触发动画? IE if some property on the data changes, is it possible to cause an animation to run? IE,如果数据的某些属性发生变化,是否有可能导致动画运行? I know I could do this with a UserControl, but I'm trying to seperate my program into more clearly defined Views and Viewmodels. 我知道我可以使用UserControl来做到这一点,但是我试图将程序分成更清晰定义的Views和Viewmodels。 I don't want Code in my View, and I don't want animations in my VM. 我不需要View中的代码,也不需要VM中的动画。

You almost answered your own question there when you said that it is able to run animations from a button.click event trigger . 当您说它能够从button.click事件触发器运行动画时,您几乎在这里回答了自己的问题。 The actual answer is yes, you can start an animation using a DataTrigger that is data bound to a view model property, or an EventTrigger using a custom RoutedEvent in the same way: 实际答案是肯定的,您可以使用与数据绑定到视图模型属性的DataTrigger来启动动画,或者使用自定义RoutedEvent来以相同方式使用EventTrigger来启动动画:

<Style>
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsAnimationRunning}" Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <SomeAnimation />
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
        </DataTrigger>
    </Style.Triggers>
</Style>

This would start the animation whenever the IsAnimationRunning property is changed from false to true . 每当IsAnimationRunning属性从false更改为true时,都将启动动画。

EDIT: On further research, I think what you need is: WPF Command with Click Event Handler 编辑:在进一步的研究中,我认为您需要的是: 具有Click事件处理程序的WPF命令

The idea is that you should call the ICommand within the event, allowing further event subscriptions. 想法是您应该在事件内调用ICommand,以允许进一步的事件订阅。 It still feels messy, since it pretty much ignores the standard command binding syntax, but it amounts to the same thing, since the command binding is still in the view. 它仍然感觉很混乱,因为它几乎忽略了标准的命令绑定语法,但是由于命令绑定仍在视图中,因此它具有相同的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM