如何使 WPF 列表框中的列中所有项目的宽度相同?
我有一个 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 IsSharedSizeScope 附加属性。 在模板定义中,将“共享大小组”附加到每列,如下所示:
...然后将 ListBox 定义为共享大小范围,以便它知道以相同的方式调整每个“大小组”的大小:
You can use the IsSharedSizeScope attached property. In your template definition, attach a "shared size group" to each column, like this:
... then define your ListBox as a shared size scope so it knows to size each "size group" the same way: