2014-09-23 175 views
-1

我正在尝试做一个简单的动画。我只是想动画一个矩形。我发现下面的代码WPF MVVM中的动画

XAML

<Window x:Class="WpfApplication2.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Rectangle Height="56" HorizontalAlignment="Left" Margin="204,104,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FFFA0000" /> 
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="21,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="rotate" /> 
    </Grid> 
</Window> 

C#

private void rotate(object sender, RoutedEventArgs e) 
{ 
    DoubleAnimation da = new DoubleAnimation(); 
    da.From = 0; 
    da.To = 360; 
    da.Duration = new Duration(TimeSpan.FromSeconds(3)); 
    da.RepeatBehavior = RepeatBehavior.Forever; 
    RotateTransform rt = new RotateTransform(); 
    rectangle1.RenderTransform = rt; 
    rt.BeginAnimation(RotateTransform.AngleProperty, da); 
} 

它完美,但我需要改变它的MVVM架构。注意元素“rectangle1”。我如何在MVVM中使用这个元素?

回答

1

它通常不适合使用MVVM方法来处理这类事情。特定UI元素的动画(几乎总是)特定于视图的代码。它特定于单个视图设计,并且可能不适用于绑定到相同视图模型的其他视图。在视图背后的代码中这样做是完全可以接受的,也可能是最好的方法。