【问题标题】:Definine one grid to hold all the items of a ListBox in stead of a grid for each using a DataTemplate使用 DataTemplate 定义一个网格来保存 ListBox 的所有项目,而不是每个项目的网格
【发布时间】:2009-07-16 12:30:25
【问题描述】:

我有一个绑定到人员列表的 ListBox。我想在网格中显示列表框的项目。我可以使用下面的代码完成此操作,但问题是使用此代码每个项目都有自己的网格。我希望一个网格包含所有项目,以便网格中的每一列自动缩放到最长字符串的宽度。我想我应该改为将数据绑定到网格?怎么样?

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition />
          <ColumnDefinition />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="{Binding Path=Name}" />
        <TextBlock Grid.Column="1" Text="{Binding Path=Age}" />
        <TextBlock Grid.Column="2" Text="{Binding Path=Gender}" />
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

【问题讨论】:

    标签: c# wpf listbox datatemplate


    【解决方案1】:

    您仍然可以使用 DataTemplate 中的 Grid 来完成此操作。您只需要在 ListBox 上指定 IsSharedSizeScope 附加属性,在要同步的 ColumnDefinitions 上指定 SharedSizeGroup 属性。

    您也可以将 ListBoxes 面板定义为 Grid,但我不建议您这样做,除非您的 Person 对象具有可轻松绑定到 Grid.Row 的 ordering 属性。

    【讨论】:

      猜你喜欢
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多