使用wpf向canvas添加形状的最佳方法?

use*_*652 3 c# wpf canvas

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

XAM*_*eLi 5

你可以用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
}
Run Code Online (Sandbox Code Playgroud)

在VM中:

public ObservableCollection<CanvasShape> Shapes {get; set;}
.....
//Add some logic to fill the collection
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)