【发布时间】:2013-04-29 07:39:27
【问题描述】:
我需要通过代码将几何对象添加到画布中。这意味着当您单击按钮时会添加一个形状。我将画布作为参数发送给函数,然后使用 canvas.children.add() 但这会破坏整个 mvvm 的想法,不是吗?有没有更好的方法?
【问题讨论】:
我需要通过代码将几何对象添加到画布中。这意味着当您单击按钮时会添加一个形状。我将画布作为参数发送给函数,然后使用 canvas.children.add() 但这会破坏整个 mvvm 的想法,不是吗?有没有更好的方法?
【问题讨论】:
您可以将ItemsControl 与Canvas 一起使用,因为它是项目面板。然后在 VM 中,您需要一个集合来保存所有项目。每个项目都应具有放置的所有属性。
因此,在代码中,它将如下所示(为简洁起见,我省略了更改通知):
物品:
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
}
在虚拟机中:
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>
【讨论】:
不,没有更好的方法。
如果您在 XAML 中定义形状,它们会以同样的方式添加到 Canvas.Children。
现在,如果您想以一种干净的 Mvvm 方式做到这一点,您可能必须对您的视图模型进行创新。我会为按钮添加一个 VM ICommand(这样您就可以连接它),在处理程序中,我会向 ObservableCollection 添加某种对象,然后在您的视图中执行一些操作以从该 ViewModel 集合创建形状(在 xaml 或代码隐藏中)
【讨论】: