我一直在試圖弄清楚如何在視圖模型更新時動態取決於所述屬性的值的情況下如何有效地觸發視圖中的動畫。使用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