2013-04-29 44 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> 
相关问题