Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

How can I make a column in a listbox in WPF the same width for all items?

I have a ListBox with an ItemTemplate consisting of a TextBlock and a ComboBox. The problem is that the width of the text inside the TextBlock is not the same for each item and the ComboBox controls are not aligned.
How can I set the TextBlock in the template so all items are the same width, that is the one of the widest?

Here is my 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>
question from:https://stackoverflow.com/questions/1102734/how-can-i-make-a-column-in-a-listbox-in-wpf-the-same-width-for-all-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the IsSharedSizeScope attached property. In your template definition, attach a "shared size group" to each column, like this:

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

... then define your ListBox as a shared size scope so it knows to size each "size group" the same way:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...