在垂直重复的ItemsControl中,如何绘制带有矩形和边距的项目? [英] How to draw items with rectangles and margin, in a vertically repeating ItemsControl?

查看:46
本文介绍了在垂直重复的ItemsControl中,如何绘制带有矩形和边距的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试可视化List<MyCustomClass>.
每个项目应为矩形(带有圆角,但这是另一个杂边),垂直重复,并在项目之间留有边距.

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>

我该如何解决? 我猜矩形对象本身是错误的方法.实际上,我认为Canvas本身可以绘制背景颜色.

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.

推荐答案

Canvas不会自动调整其内容的大小.为此,您可以使用另一个布局元素,例如Grid.但是,像您所做的那样,Canvas 便于布置孩子的位置.现在,您的Canvas的大小为0,0,这就是为什么ItemsControl面板将它们堆叠在一起的原因.

A Canvas doesn't automatically size to the content it contains. To do that you can use another layout element such as a Grid. But a Canvas is convenient for laying out the position of children, as you have done. As it is right now your Canvas has size 0,0 and that is why the ItemsControl panel is stacking them on top of each other.

如果您想继续使用Canvas,则只需自己指定大小,例如:

If you want to continue to use a Canvas, then simply specify the size yourself, e.g.:

<Canvas Width="300" Height="100" ...>

或任何合适的值对于正确的外观都是有意义的.

or whatever values make sense for the right look.

如果切换到Grid,则可以使用Margin属性指定子项的位置.请注意,默认情况下没有行或列的Grid会彼此堆叠元素,因此在这方面它与Canvas非常相似.只需使用Margin进行移动即可.

If you switch to a Grid, then you can specify the position of children using the Margin property. Note that a Grid without rows or columns by default stacks elements on top of each other, so it is very similar to a Canvas in that respect. Just shift them using Margin.

这篇关于在垂直重复的ItemsControl中,如何绘制带有矩形和边距的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆