2013-07-05 46 views
1

我想使用WPF製作簡單的動畫。我有使用拉球的帆布使用ItemTemplateSelector如何在WPF中使用MVVM實現球移動動畫?

<ItemsControl ItemsSource="{Binding Path=Cells}" Name="ItemsControlCells"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <Canvas Width="450" Height="450"> 
        </Canvas> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplateSelector> 
       <selector:Selector CellWithBall="{StaticResource CellWithBall}"/> 
      </ItemsControl.ItemTemplateSelector> 
     </ItemsControl> 

這是DataTemplate的示例。

<DataTemplate x:Key="CellWithBall"> 
     <Canvas> 
      <Rectangle Canvas.Left="{Binding Path=Position.x}" Canvas.Top="{Binding Path=Position.y}" 
         Fill="{Binding Path=BallColour}" Width="{Binding Path=Size}" Height="{Binding Path=Size}" 
         Stroke="Black" StrokeThickness="0.1"> 
       <Rectangle.InputBindings> 
        <MouseBinding Gesture="LeftClick" 
            Command="{Binding Path=DataContext.ClickedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
            CommandParameter="{Binding}" /> 
       </Rectangle.InputBindings> 
      </Rectangle> 
     </Canvas> 
    </DataTemplate> 

當移動球事件觸發器時,模型發送到查看模型路徑。路徑是球必須經過的點的列表。例如:在球場單元格中繪製球(0; 0)(意味着視圖模型中的位置設置爲(0; 0))。比我們想要將球移動到單元格(1; 1)。邏輯獲得這樣的路徑{(0; 0),(0; 1),(1; 1)}。

我如何能實現這種動畫不破壞MVVM實現?我怎樣才能將路徑傳遞給View?每一個想法將不勝感激。

+0

爲什麼你試圖迫使東西,這只是應該幫助你?我不明白爲什麼有這麼多人努力去「堅持mvvm」,只是做出非常複雜的東西...... MVVM是一種幫助,一種指導方針,如果它適合你,堅持它,並將其打破打破它。對於你的問題,處理你的自定義控件中的動畫,你的視圖模型只是通知或用於檢索重要數據。動畫應該通常只有視圖依賴(但再次,如果需要,打破它):) – dowhilefor

回答

0

如果使用MVVM,我假設你有一個視圖模型(VM)的地方。現在,我們稱之爲'CellAnimatorVM'。無論如何,假設您的ItemsView將存在於一個窗口中,您希望將該窗口的DataContext設置爲您的CellAnimatorVM類。

<Window.DataContext> 
     <local:CellAnimatorVM/> 
</Window.DataContext> 

現在,您的'Cells'對象(單元格列表)需要存在於您的CellAnimatorVM類中。您的CellAnimatorVM類將負責更改單元格列表中每個單元的位置。

爲了將這些更改傳達給您的控件,您需要將INotifyPropertyChanged添加到Cell類中,並且每當Position被設置時,您需要在setter之後調用OnPropertyChanged(「Position」)設置:

private Position _position; 

public Position Position 
{ 
    get{ return _position;} 
    set 
    { 
     _position = value; 
     OnPropertyChanged("Position"); 
    } 
} 

這應該讓你迷上了。

FYI:一個簡單的實現INotifyPropertyChanged的是如下:

#region INotifyPropertyChanged Members 

public event PropertyChangedEventHandler PropertyChanged; 

private void OnPropertyChanged(string prop) 
{ 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(prop)); 
    } 
} 

#endregion 
+0

柯蒂斯,你是對的。這是我真實的代碼。 VM是DataContext和OnPropertyChaneged用於更新View。但問題在於動畫。我從來沒有使用過動畫。只是最簡單的任務。所以我不知道要使用什麼控制或什麼。 @dowhilefor建議,使自定義控件。好主意。將盡快嘗試。 – Barada

+0

那麼你只是自動移動單元格,還是基於用戶點擊什麼時移動它們?如果您自動移動它們,WPF會在其中創建動畫。如果你在用戶點擊某些東西時移動它,那麼你仍然可以在一段時間內使用WPF從點A到點B進行動畫,並且它會這樣做。這裏有一個博客鏈接,提供有關如何進行動畫的良好信息。 http://blogs.msdn.com/b/wpfsdk/archive/2007/01/15/wpf-animations-are-easy.aspx。 – Curtis