我想使用命令来动画UIElements。我可以这样做,同时也使用MVVM吗?

时间:2015-02-10 21:49:59

标签: c# wpf .net-4.5

基本上,我不确定如何在当前情况下正确使用MVVM和/或正确使用命令。所以,我有一个View,包含一个列表框,以及我创建的一组动画对象。这些动画对象可以通过简单的公共方法Animate()进行动画处理。这里的目标是将此Animate()方法与列表框内的按钮相关联,如下所示:

正如我们在下图中所看到的,ListBox项目和动画区域内的可视元素都与ViewModel中的相同模型集合相关联,每个模型中的项目都是模板化的。例如,ListBox项被简单地定义为具有与数据项相关的一些文本,并且AnimationObjects根据数据呈现外观。我觉得这些模型不应该理解动画正在发生 - 它们是简单的数据,动画不会改变它们。 最后,我在下图中显示,我创建了两个FrameworkElement子类型,一个用于保存动画对象,另一个用于定义这些动画对象。 如何将此动画操作连接到列表框中的按钮?模型/视图模型知道动画是没有意义的,因为它不会改变我的应用程序中的任何状态 - 它只是出于视觉目的。我已经考虑过使用在AnimationObject中定义的RoutedCommand,并让按钮相应地绑定它们的命令属性,但我担心这会让每个元素同时生成动画。

为了我的缘故,我必须遵守MVVM,因为这些数据将用于许多其他情况,甚至可能是该视图的不同版本。

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

您可以在ViewModel中调用命令,即ListBox的DataContext。

CS:

public class ViewModel
{
    public ICommand AnimateObjectCommand { get; }
} 

XAML:

<DataTemplate x:Key="AnimationObjectItemTemplate">
    <Button Command="{Binding Path=DataContext.AnimateObjectCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" 
            CommandParameter="{Binding}" />
</DataTemplate>

<ListBox ItemsSource="{Binding AnimationObjects}" ItemTemplate="{StaticResource AnimationObjectItemTemplate}"/>

你的Command实现应该是一个接受CommandParameter传递的参数的实现。

    private ICommand _animateObjectCommand;
    public ICommand AnimateObjectCommand
    {
        get
        {
            if (_animateObjectCommand == null)
            {
                _animateObjectCommand = new RelayCommand<AnimationObject>( ao => { ao.Animate(); });
            }
            return _animateObjectCommand;
        }
    }

CommandParameter = {Binding}意思是this.DataContext,这是ListBox中的一个Item,它的DataContext是一个AnimationObject。