示例:WPF中应用Grid的SharedSizeGroup设置整齐的布局

一、目的:应用Grid的SharedSizeGroup设置整齐的布局

二、实现

XML 复制代码
 <ItemsControl ItemsSource="{local:GetStudents Count=5}">
     <ItemsControl.ItemTemplate>
         <DataTemplate>
             <Grid ShowGridLines="True">
                 <Grid.ColumnDefinitions>
                     <ColumnDefinition/>
                     <ColumnDefinition/>
                 </Grid.ColumnDefinitions>
                 <TextBlock Text="{Binding Address}" Grid.Column="0"/>
                 <TextBlock Text="{Binding Name}" Grid.Column="1"/>
             </Grid>
         </DataTemplate>
     </ItemsControl.ItemTemplate>
 </ItemsControl>

当我们在一个ItemsControl里面用Grid定义了两列时,显示效果如下,比较乱

一般情况我们会把Grid,的列宽设置一个固定值

这样看起来比较整齐,但是字段长度不可控制,有些会被覆盖掉,这时候需要 **SharedSizeGroup,**去控制列的宽度

三、环境

VS2022

四、示例

XML 复制代码
<ItemsControl Grid.IsSharedSizeScope="True" ItemsSource="{local:GetStudents Count=5}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid ShowGridLines="True">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition SharedSizeGroup="group1"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Address}" Grid.Column="0"/>
                <TextBlock Text="{Binding Name}" Grid.Column="1"/>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Grid.IsSharedSizeScope="True" 放在父级上,所有子元素的Grid标识了SharedSizeGroup都会列宽自动对齐

显示效果如下

五、需要了解的知识点

Grid 类 (System.Windows.Controls) | Microsoft Learn

Grid.IsSharedSizeScope Attached Property (System.Windows.Controls) | Microsoft Learn

DefinitionBase.SharedSizeGroup Property (System.Windows.Controls) | Microsoft Learn

六、源码地址

GitHub - HeBianGu/WPF-ControlDemo: 示例

GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库

GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库

七、了解更多

System.Windows.Controls 命名空间 | Microsoft Learn

https://github.com/HeBianGu

HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频

相关推荐
芝麻科技10 小时前
使用ValueConverters扩展实现枚举控制页面的显示
wpf·prism
笑非不退1 天前
Wpf Image 展示方式 图片处理 显示
开发语言·javascript·wpf
△曉風殘月〆1 天前
在WPF中实现多语言切换的四种方式
wpf·多语言切换
笑非不退1 天前
WPF C# 读写嵌入的资源 JSON PNG JPG JPEG 图片等资源
c#·wpf
He BianGu1 天前
演示:基于WPF的DrawingVisual开发的频谱图和律动图
wpf·示波器·曲线图·频谱分析仪·频谱图·高性能曲线·自绘
笑非不退5 天前
WPF 设计属性 设计页面时实时显示 页面涉及集合时不显示处理 设计页面时显示集合样式 显示ItemSource TabControl等集合样式
wpf
△曉風殘月〆5 天前
WPF中的XAML详解
wpf·xaml
ithouse5 天前
使用WPF实现一个快速切换JDK版本的客户端工具
java·开发语言·wpf
河西石头5 天前
WPF之UI进阶--控件样式与样式模板及词典
ui·wpf·样式·模板·控件样式·样式模板·样式词典
TA远方6 天前
【WPF】桌面程序开发之窗口的用户控件详解
c#·wpf·usercontrol·用户控件·控件属性