Reputation: 169
Hey guys so I have a wpf application and I want to make a 100x100 grid of squares and be able to treat it like a normal collection (List, Array etc) in my code ;
How could I do that in WPF without writing <Rectangle .../>
10,000 times?
Upvotes: 0
Views: 205
Reputation: 411
You can try to use a WrapPanel
combined with an ItemsControl
to do that :
<ItemsControl x:Name="RectanglesItemsControl">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="myNamespace:MyType">
<Rectangle Width="{Binding Width}" Height="{Binding Height}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
MyType would be a simple class with a Width
and Height
property, it would also need to implement INotifyPropertyChanged
.
You can then set your ItemsControl
's ItemsSource
to your List, or even better, an ObservableCollection<MyType>
, to register the collection changes:
RectangleItemsControl.ItemsSource = myLongCollectionFilledWithALotOfRectangles;
EDIT: You can replace WrapPanel
by anything you want, you can also use a <UniformGrid Rows="100" Columns="100" IsItemsHost="True"/>
to have 100 rows and columns.
Upvotes: 2