示例: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个人主页-哔哩哔哩视频

相关推荐
默 语2 天前
HarmonyOS7基础属性全解(八):隐私遮罩 obscured——屏幕上看得清清楚楚,录屏里只剩占位图
wpf·harmonyos
默 语2 天前
HarmonyOS7基础属性全解(四):显隐控制 visibility——藏起来、占着位、干脆不存在,是三回事
wpf
陈仓主教2 天前
WPF 菜单(Menu)控件详解与使用—WPF 中的控件(23)--菜单(Menu)
wpf
qq_452396234 天前
第十篇:分布式事务架构如何设计?从 Outbox 到 Saga 的生产级选型指南
分布式·架构·wpf
凌镜icecraft9 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
光泽雨14 天前
控件Password附加属性
wpf
samble18 天前
从零搭建半导体设备上位机(十二):参数设置页,表单校验、范围校验与配方联动
wpf·数据校验·validationrule
samble1 个月前
从零搭建半导体设备上位机(九):拖拽与交互,Adorner、DragDrop 与晶圆拖放信息
wpf·拖拽·adorner
郝学胜-神的一滴1 个月前
AI 编程智能体 27:吃透MCP通信机制
人工智能·python·langchain·wpf·numpy·scikit-learn
波力海苔夹心脆6751 个月前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典