2013-04-29 46 views
3

我需要通過代碼將幾何對象添加到畫布中。意思是當您單擊按鈕時添加了形狀。我將canvas作爲參數發送給函數,然後使用canvas.children.add(),但是這種方式會影響整個mvvm的想法,不是嗎?有沒有更好的方法來做到這一點?使用wpf將圖形添加到畫布的最佳方法是什麼?

回答

-1

不,沒有更好的方法來做到這一點。

如果您在XAML中定義形狀,它們將Add()'編輯到Canvas.Children中的方式相同。

現在,如果你想以乾淨的Mvvm方式來做到這一點,那麼你可能不得不用你的視圖模型來獲得創造性。我會爲該按鈕添加一個VM ICommand(因此您可以連接它),在處理程序中,我將某種對象添加到ObservableCollection,然後在視圖中執行某些操作以從該ViewModel集合創建形狀(在xaml或代碼隱藏中)

5

您可以使用ItemsControlCanvas作爲它的項目面板。然後在虛擬機中,您需要一個集合來保存所有項目。每個項目應具有所有放置屬性。

所以,在代碼中,它看起來像這樣(我省略爲簡潔變更通知):

項:

public class CanvasShape : INotifyPropertyChanged 
{ 
    public double Top {get; set;}//TODO: add change notification 
    public double Left {get; set;}//TODO: add change notification 
    public Geometry PathData {get; set;}//TODO: add change notification 
} 

在VM:

public ObservableCollection<CanvasShape> Shapes {get; set;} 
..... 
//Add some logic to fill the collection 

在XAML中:

<!--The DataContext here is the VM--> 
<ItemsControl ItemsSource="{Binding Shapes}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <Canvas IsItemsHost="True"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemContainerStyle> 
     <Style> 
      <!--These setters will control the position of the shape; the DataContext here is CanvasShape--> 
      <Setter Property="Cavas.Top" Value="{Binding Top}"/> 
      <Setter Property="Cavas.Left" Value="{Binding Left}"/> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Path Data="{Binding PathData}" 
        ....... 
        /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
相關問題