在 ItemsControlDataTemplate 中设置画布属性

我正在尝试数据绑定到这个 ItemsControl:

<ItemsControl ItemsSource="{Binding Path=Nodes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

通过使用这个 DataTemplate,我试图单独地将我的 Node元素正确地放置在 Canvas上:

<DataTemplate DataType="{x:Type Model:EndNode}">
<Controls:EndNodeControl Canvas.Left="{Binding Path=XPos}" Canvas.Top="{Binding Path=YPos}" />
</DataTemplate>

然而,它并没有像预期的那样工作。我的所有节点元素都在相同的位置相互叠加绘制。对于如何实现这一点有什么建议吗?

26306 次浏览

The attached properties only work on direct children of the Canvas. ItemsControl will place ContentPresenter controls as its direct children, so you might want to add a style for that as well:

<ItemsControl ItemsSource="{Binding Path=Nodes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Path=XPos}" />
<Setter Property="Canvas.Top" Value="{Binding Path=YPos}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>