简体   繁体   中英

WPF - How to fill the window with squares

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?

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.

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