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.
A
Canvasdoesn’t automatically size to the content it contains. To do that you can use another layout element such as aGrid. But aCanvasis convenient for laying out the position of children, as you have done. As it is right now yourCanvashas size0,0and that is why theItemsControlpanel 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 theMarginproperty. Note that aGridwithout rows or columns by default stacks elements on top of each other, so it is very similar to aCanvasin that respect. Just shift them usingMargin.