How to draw items with rectangles and margin, in a vertically repeating ItemsControl?
I'm trying to visualize a List<MyCustomClass>
.
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>
<TextBl开发者_运维技巧ock 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 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
.
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>
精彩评论