gpt4 book ai didi

c# - WPF:同步 ItemsControl 中所有项目的宽度

转载 作者:行者123 更新时间:2023-12-02 09:23:14 32 4
gpt4 key购买 nike

是否可以将 WrapPanel 中所有 TextBlock 的宽度调整为 WrapPanel 中最大 TextBlock 的大小?最终结果应该是包含“一些数据”的控件的宽度与包含“甚至比以前更多的数据”的控件的宽度相同。我已附上我的初始代码作为起点。我使用字符串作为示例,但集合数据和模板可以是任何内容,因此我不能依赖字符串的长度。

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Collections:ArrayList x:Key="data">
<System:String>Some data</System:String>
<System:String>Some more data</System:String>
<System:String>Even more data than before</System:String>
</Collections:ArrayList>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource data}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderThickness="1" BorderBrush="Black">
<TextBlock Text="{Binding}"></TextBlock>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>

以及所需输出的图像:

Desired output

最佳答案

使用共享尺寸网格:

<ItemsControl ItemsSource="{StaticResource data}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="ColumnSize" />
</Grid.ColumnDefinitions>
<Border Margin="5" BorderThickness="1" BorderBrush="Black">
<TextBlock Text="{Binding}"></TextBlock>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

所有列都保证具有相同的宽度,因为它们共享一个大小组。由于它们的大小是自动调整的,因此它们也会调整为任何网格内容的最大实例。

关于c# - WPF:同步 ItemsControl 中所有项目的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28995443/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com