Reputation: 1436
I'm trying to create a grid that will take in a one dimensional collection (in my testing i'm using a string array, but this could be expanded to custom objects), and then display them this way:
Item1 Item2
Item3 Item4
Item5
I understand how to do this explicitly using Row/Col definitions, however I want to be able to create a XAML snippet that I can say, "Here is a collection of items, I want X number of columns", and it will create that structure. It seems like such a simple thing but I cannot seem to figure it out. Is this possible?
Thanks
Upvotes: 0
Views: 167
Reputation: 17402
You can use a WrapPanel
, but some trickery will need to be involved so that there's always 2 columns.
See below:
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel ItemWidth="200"
MaxWidth="400"
MinWidth="400"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Code-behind (for demo):
{
public MainWindow()
{
InitializeComponent();
DataContext = new Data
{
Items = new List<string>
{
"item 1",
"item 2",
"item 3",
"item 4",
"item 5",
"item 6",
"item 7",
}
};
}
}
public class Data
{
public List<string> Items { get; set; }
}
Upvotes: 1
Reputation: 112
The WrapPanel class can do that. MSDN reference
Simply use it in XAML with
<WrapPanel Orientation="Horizontal"/>
And add elements with
WrapPanel.Children.Add(UIElement);
in code behind.
Upvotes: 1