peter
peter

Reputation: 13491

How to bind a canvas to a list of rectangles

Using WPF I have a list of rectangles (which can have an undefined number of rectangles in it), and a canvas. I want to position those rectangles on the canvas using data binding.

I have tried using an items control, and seems to stack each item on top of the next one like a vertical stack panel.

All my rectangles have the co-ordinates 0,0, but they are all on top of each other down the canvas.

Any alternatives to using an items control?

Upvotes: 5

Views: 2662

Answers (1)

brunnerh
brunnerh

Reputation: 184376

You need to account for the wrapping of the items when bound:

<ItemsControl ItemsSource="{Binding Data}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Top" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- Item Template -->
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 9

Related Questions