1

I have UserControl that includes several rectangles:

<StackPanel>
    <Rectangle Height="70" Width="100" x:Name="Image1" />
    <Rectangle Height="70" Width="100" x:Name="Image2" />
    <Rectangle Height="70" Width="100" x:Name="Image3" />
</StackPanel>

How can I create various number of rectangles via data binding and set rectangles width and height (and other properties) instead of this static hardcode approach?

Thank you in advance!

user149691
  • 587
  • 1
  • 5
  • 19

1 Answers1

2

Generally, you would have an ItemsControl (or a ListBox, etc.) and modify its item template to show the rectangles:

<ItemsControl ItemsSource={Binding MyRectangles}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Width="{Binding Width}" Height="{Binding Height}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Note that this assumes the data context has a MyRectangles collection, and each item within that collection has a Width and Height property.

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92