我一直在试图弄清楚如何在视图模型更新时动态取决于所述属性的值的情况下如何有效地触发视图中的动画。使用MVVM的动态视图动画
我用一个View和ViewModel在一个简单的应用程序中重新创建了我的问题。这里的目标是通过使用ColorAnimation来转换矩形的颜色变化。作为参考,我一直在使用Josh Smith的MVVM Foundation包。
示例项目可以downloaded here.
总之,我想动画在视图每当颜色属性更改颜色过渡。
MainWindow.xaml
<Window x:Class="MVVM.ColorAnimation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ColorAnimation="clr-namespace:MVVM.ColorAnimation" Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ColorAnimation:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Rectangle Margin="10">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Color}"/>
</Rectangle.Fill>
</Rectangle>
<StackPanel Orientation="Horizontal" Grid.Row="1">
<Button Command="{Binding BlueCommand}" Width="100">Blue</Button>
<Button Command="{Binding GreenCommand}" Width="100">Green</Button>
</StackPanel>
</Grid>
</Window>
MainWindowViewModel.cs
namespace MVVM.ColorAnimation
{
using System.Windows.Input;
using System.Windows.Media;
using MVVM;
public class MainWindowViewModel : ObservableObject
{
private ICommand blueCommand;
private ICommand greenCommand;
public ICommand BlueCommand
{
get
{
return this.blueCommand ?? (this.blueCommand = new RelayCommand(this.TurnBlue));
}
}
private void TurnBlue()
{
this.Color = Colors.Blue;
}
public ICommand GreenCommand
{
get
{
return this.greenCommand ?? (this.greenCommand = new RelayCommand(this.TurnGreen));
}
}
private void TurnGreen()
{
this.Color = Colors.Green;
}
private Color color = Colors.Red;
public Color Color
{
get
{
return this.color;
}
set
{
this.color = value;
RaisePropertyChanged("Color");
}
}
}
}
反正从视图触发ColorAnimation而不是值之间的即时转变?我目前这样做的方式是另一个应用程序非常混乱,因为我通过ViewModel
属性设置ViewModel,然后使用PropertyObserver监视值更改,然后创建动画并从代码隐藏中触发它:
this.colorObserver = new PropertyObserver<Player>(value)
.RegisterHandler(n => n.Color, this.CreateColorAnimation);
在我处理很多颜色和许多潜在动画的情况下,这会变得非常混乱,并且混淆了我手动将ViewModel传递给View的事实,而不是简单地通过ResourceDictionary中。我想我也可以在DataContextChanged
事件中做到这一点,但是有没有更好的方法?
该项目的链接不再有效。 – itsho 2013-11-12 09:12:08