P:初学WPF-谁决定了控件在容器中的位置?

来源:互联网 发布:windows管理员权限cmd 编辑:程序博客网 时间:2024/06/06 00:10

以Button为示例元素,拖放到Window窗体中,很显然

    HorizonalAlignment=Left – 左对齐;

    VerticalAlignment=Top – 上对齐;

    Margin –元素的外边距 (Left/Top/Right/Bottom)

是这三个属性同时控制Button的位置,等效于Location:


而正是这样的设置方式,才引起了一系列的问题:

(1)Margin边距 – 这个好说,不解释。XAlignment对齐这个也好说,可为什么每个通过拖拽方式添加的控件上都会“强制性地”设置这两个属性?

每个控件本身自带有默认值,在没有手动设置属性值时仍然可以正常渲染。显然XAlignment非默认值。那默认值会是什么呢,又会出现什么样的效果呢?

最简单的办法,直接删除XAlignment。 而在属性窗口中查看其值为 Stretch

[MSDN: A horizontalalignment setting, as a value of the enumeration. The default is Stretch.]


(2)看上面的那个效果图,不考虑Margin的话,也就是居中的效果了:


等等,怎么是96?不应该是:(WinWidth - BtnWidth)/ 2 = (300 - 100) / 2 = 100

8px丢失在哪里了?(OMG,这个还算是问题?是不是吃错药了,脑袋抽筋了?醒醒~醒醒。。。)

 

窗体程序默认是有边框的:

    

而正好说明了那“丢失的”4px 是左/右/下边框的宽度。

 

索性就将Window定义为无边框窗体,修改属性:

    

 WindowStyle="None" AllowsTransparency="True"

完整地显示了居中对齐效果:


(3)再等等,居中对齐的效果?换句话说 Strech 和 Center的作用一样的?非也,非也!

     Center的解释是:

        [MSDN: Anelement aligned to the center of the layout slot for theparent element.]

     Stretch的解释是:

        [MSDN: Anelement stretched to fill the entire layout slot of theparent element.]

看到没有,是拉伸控件来填充这个父容器。可是上面那N多个图中都不是Fill的效果!

那是因为Button 定义了宽和高:

   [MSDN: When Height and Width properties are explicitly set on anelement, these measurements take higherprecedentduring layout and will cancel the typical effects of setting HorizontalAlignment to Stretch. ]

也就是控件的Height & Width 造成了Stretch 和 Center在视觉上的相同效果。

 

未设置宽高的Button,在Center的布局下,等效于行内元素span,Height & Width取决于文本的多少和字体等因素。如效果图:

 

未设置宽高的Button,在Stretch的布局下,等效于Dock.Fill。如效果图:


参考资料:

https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.horizontalalignment(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.windows.horizontalalignment(v=vs.110).aspx

http://blog.csdn.net/johnsuna/article/details/1893319


0 0