DataTemplate 为列表中的第一项提供正确的结果,但为 WPF 中的第二项提供错误的结果
我的控件中有以下项目:
<Canvas Name="canvasTrack" Height="{Binding CanvasHeight}" Width="{Binding CanvasWidth}">
<ItemsControl
ItemsSource="{Binding Path=CurrentSegments}"
ItemTemplate="{StaticResource BegSegmentTemplate}">
</ItemsControl>
</Canvas>
以及以下 DataTemplate
:
<DataTemplate x:Key="BegSegmentTemplate">
<Ellipse Height="10" Width="10" Margin="{Binding EntryPoint}" Fill="Black" HorizontalAlignment="Center" />
</DataTemplate>
然后我将其绑定到其中包含两个项目的 ObservableCollection
。当我运行该程序时,会出现两个省略号。第一个位于画布上的正确位置,但第二个位于“随机”位置。我检查了绑定的号码,一切正常。我可能会错过什么?
I have the following Item in my control:
<Canvas Name="canvasTrack" Height="{Binding CanvasHeight}" Width="{Binding CanvasWidth}">
<ItemsControl
ItemsSource="{Binding Path=CurrentSegments}"
ItemTemplate="{StaticResource BegSegmentTemplate}">
</ItemsControl>
</Canvas>
And the following DataTemplate
:
<DataTemplate x:Key="BegSegmentTemplate">
<Ellipse Height="10" Width="10" Margin="{Binding EntryPoint}" Fill="Black" HorizontalAlignment="Center" />
</DataTemplate>
I then have it bound to an ObservableCollection
that has two items in it. When I run the program two ellipses appear. The first one is in the correct spot on my canvas but the second one is in a 'random' spot. I have checked the numbers that are being bound and everything appears normal. What could I be missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,
ItemsControl
循环遍历其项目并将每个项目放入StackPanel
中,因此您的最终标记基本上如下所示:如果您想循环遍历项目并放置它们位于基于某些绑定值的
Canvas
上,您需要覆盖ItemsPanelTemplate
以使用Canvas
而不是StackPanel
代码>,然后应用您在ItemContainerStyle
中的定位,以便您在ContentPresenter
上设置定位,而不是Ellipse
这将使您的最终结果如下所示:
实现此目的的一些示例代码如下:
请参阅此链接对于一些使用
ItemsControl
的示例By default, an
ItemsControl
loops through it's items and puts each of them in aStackPanel
, so your end markup basically looks like this:If you want to loop through items and place them on a
Canvas
based on some bound value, you need to overwrite theItemsPanelTemplate
to use aCanvas
instead of aStackPanel
, and apply your positioning in theItemContainerStyle
so that you are setting the positioning on theContentPresenter
, and not theEllipse
This will make your end result look like:
Some example code to achieve this would be:
See this link for some samples using an
ItemsControl
尝试在
ItemsControl
中指定ItemsPanel
:Try specifying an
ItemsPanel
in yourItemsControl
: