Reputation: 393
How can I make dynamic set columns in grid or what grid analog should I use?
I have a List
, for example List<List<string>> = {{a},{b,c},{d,e},{f,g,h}}
And i need to make from each element a row, and sub-elements should be stretched. like on the picture below. So if there one element, it takes all grid width, if there two sub-elements each takes half of grid's width and so on. I got xaml from here here it is
<Page>
<Page.Resources>
<DataTemplate x:Key="DataTemplate_Level2">
<Button Content="{Binding}" Margin="1,1,1,1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplate_Level1">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{StaticResource DataTemplate_Level2}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</Page.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding}" x:Name="lst" ItemTemplate="{StaticResource DataTemplate_Level1}"/>
</Grid>
</Page>
But it can't streach sub-elementslike I need, like this:
Upvotes: 1
Views: 188
Reputation: 8111
Try this:
<ItemsControl HorizontalAlignment="Stretch">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}" HorizontalAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" Margin="1,1,1,1" VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ItemsControl>
And this is how it looks
EDIT:
Since Universal App doesn't support UniformGrid
, I created my own panel:
public class UniformGridSingleLine : Panel
{
protected override Size MeasureOverride(Size availableSize)
{
foreach (UIElement child in Children)
child.Measure(availableSize);
return new Size(double.IsPositiveInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsPositiveInfinity(availableSize.Height) ? Children.Cast<UIElement>().Max(x => x.DesiredSize.Height) : availableSize.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
Size cellSize = new Size(finalSize.Width / Children.Count, finalSize.Height);
int col = 0;
foreach (UIElement child in Children)
{
child.Arrange(new Rect(new Point(cellSize.Width * col, 0), new Size(cellSize.Width, child.DesiredSize.Height)));
col++;
}
return finalSize;
}
}
Just replace UniformGrid
with UniformGridSingleLine
in the XAML above (don't forget the namespace)
Upvotes: 1