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

标签 c# wpf xaml wpf-controls

是否可以将 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/

相关文章:

c# - 为什么我的字典查找会出现 SQL 超时错误?

c# - 是否可以在数据库中保存正在运行的计时器?

c# - 如何使用 Selenium for C# 通过 XPath 查找文本?

c# - OxyPlot 中的多个 LineSeries 绑定(bind)

c# - 桥接来自两个绑定(bind)源的 DependencyProperty

c# - WPF MVVM 是否有 IValueConverter 的替代方案

wpf - 模糊的 XAML 矢量图形

从 SQLite 数据库生成 C# POCO

c# - 为什么 Xamarin.Form XAML 文件中 StackLayout 的子元素超出屏幕范围?

c# - MahApps PasswordBox 不显示清除按钮