UWP中如何实现GridView/ListBox项居中对齐及末行特殊排布?
自定义3列GridView/ListBox末行对齐方案
需求规则
- 每行固定展示3个条目
- 末行仅剩1个条目时,该条目显示在第二列位置
- 末行剩2个条目时,第一个展示在第一、二列中间,第二个展示在第二、三列中间,两个条目均匀分布在整行宽度
效果示例
- 总条目数为7(末行1个)效果:

- 总条目数为8(末行2个)效果:

具体实现
前端Web端(CSS Grid方案)
通过Grid布局结合伪类判断末行剩余元素数量,动态调整位置:
.grid-wrap { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; } .grid-item { height: 100px; background: #eee; border-radius: 4px; } /* 末行1个元素:总数量为3n+1 */ .grid-item:nth-last-child(1):nth-child(3n + 1) { grid-column: 2/3; } /* 末行2个元素:总数量为3n+2 */ .grid-item:nth-last-child(2):nth-child(3n + 1) { justify-self: end; margin-right: 8px; /* 取gap的一半 */ } .grid-item:nth-last-child(1):nth-child(3n + 2) { justify-self: start; margin-left: 8px; /* 取gap的一半 */ }
WPF/WinUI桌面端(自定义布局方案)
重写UniformGrid的排列逻辑,动态调整末行元素偏移:
public class AlignLastRowUniformGrid : UniformGrid { protected override Size ArrangeOverride(Size arrangeSize) { int total = Children.Count; int cols = Columns; if (cols != 3 || total % cols == 0) return base.ArrangeOverride(arrangeSize); int lastRowCount = total % cols; double colWidth = arrangeSize.Width / cols; int lastRowStart = (total / cols) * cols; var res = base.ArrangeOverride(arrangeSize); if (lastRowCount == 1) { var ele = Children[lastRowStart]; ele.Arrange(new Rect(ele.ArrangeRect.X + colWidth, ele.ArrangeRect.Y, ele.ArrangeRect.Width, ele.ArrangeRect.Height)); } else if (lastRowCount == 2) { var ele1 = Children[lastRowStart]; var ele2 = Children[lastRowStart + 1]; double offset = colWidth * 0.5; ele1.Arrange(new Rect(ele1.ArrangeRect.X + offset, ele1.ArrangeRect.Y, ele1.ArrangeRect.Width, ele1.ArrangeRect.Height)); ele2.Arrange(new Rect(ele2.ArrangeRect.X + offset, ele2.ArrangeRect.Y, ele2.ArrangeRect.Width, ele2.ArrangeRect.Height)); } return res; } }
使用时将GridView的ItemsPanel设置为该自定义UniformGrid即可。
内容的提问来源于stack exchange,提问作者SHIFAS KS
相关产品推荐
相关产品推荐

