如何使 WPF 列表框中的列对于所有项目具有相同的宽度? [英] How can I make a column in a listbox in WPF the same width for all items?
问题描述
我有一个 ListBox
和一个由 TextBlock
和一个 ComboBox
组成的 ItemTemplate
.问题是 TextBlock
内的文本宽度对于每个项目都不相同,并且 ComboBox
控件未对齐.
如何在模板中设置 TextBlock
以使所有项目的宽度相同,即最宽的项目之一?
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?
这是我的 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>
推荐答案
您可以使用 IsSharedSizeScope 附加属性.在您的模板定义中,将共享尺寸组"附加到每一列,如下所示:
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>
...然后将您的 ListBox 定义为共享大小范围,以便它知道以相同的方式调整每个大小组"的大小:
... 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>
这篇关于如何使 WPF 列表框中的列对于所有项目具有相同的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!