简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM