2

我需要通过代码将几何对象添加到画布中。这意味着当您单击按钮时会添加一个形状。我将画布作为参数发送给函数,然后使用 canvas.children.add() 但这会破坏整个 mvvm 的想法,不是吗?有更好的方法吗?

4

2 回答 2

4

您可以使用ItemsControlCanvas的项目面板。然后在 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>
于 2013-04-29T10:32:15.827 回答
-1

不,没有更好的方法可以做到这一点。

如果您在 XAML 中定义形状,它们会以相同的方式添加到 Canvas.Children。

现在,如果你想以一种干净的 Mvvm 方式做到这一点,你可能必须对你的视图模型进行创造性的思考。我会为按钮添加一个 VM ICommand(这样您就可以连接它),在处理程序中,我会向 ObservableCollection 添加某种对象,然后在您的视图中执行某些操作以从该 ViewModel 集合创建形状(在 xaml 或代码隐藏中)

于 2013-04-29T09:34:30.137 回答