如何在垂直重复的 ItemsControl 中绘制带有矩形和边距的项目?
我正在尝试可视化 List
。
每个项目应该在一个矩形中(带有圆角,但这是另一回事),垂直重复,项目之间留有边距。
我已经尝试过这个,但项目重叠:
<ItemsControl Name="ItemsControl1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Canvas Margin="10,10,10,10" Background="CornflowerBlue" >
<Rectangle Fill="Blue" Stroke="Blue" Width="350" Height="100">
</Rectangle>
<TextBlock Text="{Binding Headline}" Canvas.Left="25" Canvas.Top="10" />
<TextBlock Text="{Binding MyDate}" Canvas.Left="55" Canvas.Top="40"/>
<Button Content="Click me" Click="Button_Click" Width="80" Height="25" Canvas.Left="200" Canvas.Top="20" />
</Canvas>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我该如何解决这个问题? 我猜矩形对象本身是错误的方法。实际上我认为画布本身能够绘制背景颜色。
I'm trying to visualize a List<MyCustomClass>
.
Each item should be in a rectangle (with rounded corners, but that is another mattter), repeated vertically with a margin between the items.
I've tried this, but the items are overlapping:
<ItemsControl Name="ItemsControl1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Canvas Margin="10,10,10,10" Background="CornflowerBlue" >
<Rectangle Fill="Blue" Stroke="Blue" Width="350" Height="100">
</Rectangle>
<TextBlock Text="{Binding Headline}" Canvas.Left="25" Canvas.Top="10" />
<TextBlock Text="{Binding MyDate}" Canvas.Left="55" Canvas.Top="40"/>
<Button Content="Click me" Click="Button_Click" Width="80" Height="25" Canvas.Left="200" Canvas.Top="20" />
</Canvas>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
How can I fix this?
I guess the rectangle object itself is the wrong approach. Actually I thought the Canvas itself would be able to draw a background color.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Canvas
不会自动调整其包含的内容的大小。为此,您可以使用另一个布局元素,例如Grid
。但是Canvas
可以方便地布置子元素的位置,就像您所做的那样。现在,您的Canvas
的大小为0,0
,这就是ItemsControl
面板将它们堆叠在一起的原因。如果您想继续使用
Canvas
,则只需自己指定大小,例如:或任何对正确外观有意义的值。
如果切换到
Grid
,则可以使用Margin
属性指定子项的位置。请注意,默认情况下没有行或列的 Grid 会将元素堆叠在一起,因此在这方面它与 Canvas 非常相似。只需使用Margin
移动它们即可。A
Canvas
doesn't automatically size to the content it contains. To do that you can use another layout element such as aGrid
. But aCanvas
is convenient for laying out the position of children, as you have done. As it is right now yourCanvas
has size0,0
and that is why theItemsControl
panel is stacking them on top of each other.If you want to continue to use a
Canvas
, then simply specify the size yourself, e.g.:or whatever values make sense for the right look.
If you switch to a
Grid
, then you can specify the position of children using theMargin
property. Note that aGrid
without rows or columns by default stacks elements on top of each other, so it is very similar to aCanvas
in that respect. Just shift them usingMargin
.您是否尝试过设置
ItemsPanel
模板:Have you tried setting the
ItemsPanel
template: