WPF布局系统Grid中Margin和对其方式组合效果

我们都知道,在WPF布局系统中控件分配的空间是一个矩形空间,根据影响布局的属性Margin、VerticalAlignment、HorizontalAlignment、Padding等,父级容器会分配给子控件一个空间(元素边界框,可以使用LayoutInformation.GetLayoutSlot(element)获取),然后将子控件填充在其中。今天在项目中碰到一个计算偏移量的问题,一直没有计算正确,主要是在控件居中的时候Margin理解出错,一开始理解成了先对齐然后设置Margin,实际上应该理解成先设置Magin,然后设置对齐方式。例如Margin为(50,0,0,0)HorizontalAlignment=”Center”,假设父容器宽度为ParentWidth,子元素宽度为ChildWidth。如果理解成先居中在设置Margin,元素左上角点为:50+(ParentWidth-ChildWidth)/2;如果理解成先设置Margin然后对齐,元素左上角点为:50+(ParentWidth-50)/2-ChildWidth/2=50/2+(ParentWidth-ChildWidth)/2;可见实际上相差了Margin.Left一半的数值。

猜你喜欢

转载自blog.csdn.net/yulongguiziyao/article/details/79272607