【问题标题】:How can I make a column in a listbox in WPF the same width for all items?如何使 WPF 列表框中的列对于所有项目具有相同的宽度?
【发布时间】:2023-04-11 11:00:01
【问题描述】:

我有一个ListBox 和一个ItemTemplate,由一个TextBlock 和一个ComboBox 组成。问题是 TextBlock 内的文本宽度对于每个项目都不相同,并且 ComboBox 控件未对齐。
如何在模板中设置TextBlock,使所有项目的宽度相同,即最宽的项目之一?

这是我的 xaml:

<ListBox MinHeight="100" ItemsSource="{Binding Trainees}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Margin="1">
        <Grid.ColumnDefinitions>
          <ColumnDefinition />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock VerticalAlignment="Center" Grid.Column="0">
          <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}, {1}">
              <Binding Path="LastName" />
              <Binding Path="FirstName" />
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>
        <ComboBox HorizontalAlignment="Left" Grid.Column="1"
            ItemsSource="{Binding Source={StaticResource Functions}}" SelectedValue="{Binding Path=Function}"
            MinWidth="100" />
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

【问题讨论】:

    标签: wpf listbox width itemtemplate


    【解决方案1】:

    您可以使用IsSharedSizeScope 附加属性。在您的模板定义中,将“共享尺寸组”附加到每一列,如下所示:

    <Grid.ColumnDefinitions>
        <ColumnDefinition SharedSizeGroup="col1" />
        <ColumnDefinition SharedSizeGroup="col2" />
    </Grid.ColumnDefinitions>
    

    ...然后将您的 ListBox 定义为共享大小范围,以便它知道以相同的方式调整每个“大小组”的大小:

    <ListBox Grid.IsSharedSizeScope="True">...</ListBox>
    

    【讨论】:

    • 很好的答案,但很难相信任何从 '1' 开始计数的人... ;-)
    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2012-09-15
    • 2020-12-28
    相关资源
    最近更新 更多