【问题标题】:How to give dynamic width to gridview items (text block)?如何为gridview项目(文本块)提供动态宽度?
【发布时间】:2018-08-27 22:21:11
【问题描述】:

我正在开发一个 Windows 10 UWP 和一个 Windows Phone 8.1 项目。在项目中,有类似 Instagram 的标签,可以在图片中看到。这些标签使用 GridView 打印在屏幕上。问题是我无法通过它们的内容使 GridView 项目的宽度动态化。它采用第一个项目的宽度,并为所有其他项目提供相同的宽度。对于较短的单词,这不是问题,但较长单词的某些字母不可见。

这是问题的屏幕截图。

我写的代码;

<GridView SelectionMode="None" ItemsSource="{Binding TagsArray}" ScrollViewer.IsHorizontalRailEnabled="True">
  <GridView.ItemTemplate>
    <DataTemplate>
      <Grid>
         <TextBlock x:Name="tagButton" Tapped="tagButton_Tapped" FontWeight="Medium" Text="{Binding}" Foreground="#063076" FontSize="11" HorizontalAlignment="Left"/>
      </Grid>
    </DataTemplate>
  </GridView.ItemTemplate>
  <GridView.ItemContainerStyle>
    <Style TargetType="GridViewItem">
      <Setter Property="Margin" Value="0,-15,0,-15"/>
      <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
  </GridView.ItemContainerStyle>
  <GridView.ItemsPanel>
    <ItemsPanelTemplate>
      <ItemsWrapGrid Orientation="Horizontal"/>
    </ItemsPanelTemplate>
  </GridView.ItemsPanel>
</GridView>

【问题讨论】:

  • 我完成了自己的 WrapGrid 的编写

标签: c# xaml uwp windows-phone-8.1 windows-10-mobile


【解决方案1】:

我建议您使用 WrapPanel 中的 UWP Community Toolkit 来实现此目的。

您可以通过替换 ItemsPanel 在 GridView 中使用它:

    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <toolkit:WrapPanel Orientation="Horizontal" AllowDrop="True">
            </toolkit:WrapPanel>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

这是一个完整的例子:

    <GridView x:Name="ItemGrid" Width="450" HorizontalAlignment="Left" VerticalAlignment="Bottom">
        <GridView.ItemTemplate>
            <DataTemplate >
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </GridView.ItemTemplate>
        <GridView.ItemsPanel>
            <ItemsPanelTemplate>
                <controls:WrapPanel Orientation="Horizontal" AllowDrop="True">
                </controls:WrapPanel>
            </ItemsPanelTemplate>
        </GridView.ItemsPanel>
    </GridView>

与以下集合一起使用时:

        var ite = new ObservableCollection<string>();
        ite.Add("#tag1");
        ite.Add("#a");
        ite.Add("#tag3");
        ite.Add("#differ");
        ite.Add("#tag5");
        ite.Add("#longertag");
        ite.Add("#verylongtag");
        ite.Add("#tag1");

        this.ItemGrid.ItemsSource = ite;

提供以下输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2012-06-23
    • 2021-09-14
    相关资源
    最近更新 更多