如何让 itemtemplate 知道它包含的模板?
我希望这个 Ellipse 从其相应的 BallViewModel 获取其坐标,并使用它们来确定其在画布内的位置。 球列表绑定到主视图模型中的 List
,因此我选择了一个具有画布面板的 itemsControl。
这种做法正确吗?
如果我尝试绑定到 itemcontainerstyle 内的 X 和 Y,那么它并不特定于某个球。
无论我在 Canvas.bottom 或 canvas.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>
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.
Is this approach correct?
If I try to bind to X and Y inside an itemcontainerstyle, then it's not specific to a certain ball.
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将 ItemTemplate 与 ItemControls 一起使用时,它不会直接将省略号放在画布上,而是将它们包装到 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: