动态列绑定

Dynamic column binding

如何在网格中动态设置列或者我应该使用什么网格模拟?

我有一个List,例如List<List<string>> = {{a},{b,c},{d,e},{f,g,h}} 而且我需要从每个元素制作一行,并且应该拉伸子元素。如下图所示。因此,如果有一个元素,则它占用所有网格宽度,如果有两个子元素,每个子元素占用网格宽度的一半,依此类推。我从 here 得到 xaml 这里是

<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>

但是它不能像我需要的那样拉伸子元素,像这样:

试试这个:

<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>

这是它的样子

编辑:

由于 Universal App 不支持 UniformGrid,我创建了自己的面板:

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;
  }
}

只需将上面XAML中的UniformGrid替换为UniformGridSingleLine即可(不要忘记命名空间)

问题已通过使用 this post 解决。