How to draw items with rectangles and margin, in a vertically repeating ItemsControl?

吃可爱长大的小学妹 提交于 2019-12-11 10:28:13

问题


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.


回答1:


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.

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.

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.




回答2:


Have you tried setting the ItemsPanel template:

<ItemsControl ItemsSource="{Binding FeedItems}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            ... etc ...
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>   


来源:https://stackoverflow.com/questions/6481109/how-to-draw-items-with-rectangles-and-margin-in-a-vertically-repeating-itemscon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!