问题描述
我希望这个Ellipse从其对应的BallViewModel中获取其坐标,并使用它们来确定其在画布中的位置.球列表绑定到mainviewmodel中的List<BallVM>
,因此我选择了一个具有画布面板的itemsControl.
I want this Ellipse to get its coordinates from its corresponding BallViewModel, and to use them to determine its location inside a canvas.The list of balls is bound to List<BallVM>
in the mainviewmodel and thus I chose an itemsControl which has a canvas panel.
这种方法正确吗?
如果我尝试在itemcontainerstyle内绑定到X和Y,那么它并不特定于某个球.
If I try to bind to X and Y inside an itemcontainerstyle, then it's not specific to a certain ball.
无论我在Canvas.bottom或canvas.left属性中设置什么,椭圆形始终位于左上方.
No matter what I set in the Canvas.bottom or canvas.left properties the ellipse is always at the top left.
<Grid>
<ItemsControl ItemsSource="{Binding Balls}" Background="red">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas MouseMove="Canvas_MouseMove" Background="Blue"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type VM:BallVM}">
<Ellipse Canvas.Bottom="{Binding Y}" Canvas.Left="{Binding X}" Width="100" Height="100" Fill="Red"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
推荐答案
将ItemTemplate与ItemControls一起使用时,它不会直接将Elippes放在Canvas上,而是将它们包装到ContentPresenter中.因此,您必须在ItemsPresenter上应用canvas.Bottom/Left属性.您可以使用ItemContainerStyle做到这一点:
When you use an ItemTemplate with an ItemControls it does not directly put your Elippses on the Canvas but wraps them into an ContentPresenter. So you have to apply your canvas.Bottom/Left properties on the ItemsPresenter. You can can do this with the ItemContainerStyle:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Bottom" Value="{Binding Y}" />
<Setter Property="Canvas.Left" Value="{Binding X}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type VM:BallVM}">
<Ellipse Width="100" Height="100" Fill="Red"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
这篇关于如何使itemtemplate知道其包含的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!