WPF中如何将一个控件附加到另一个控件?
我的窗口右下角有一个 ListBox
,我想在该 ListBox
的最左侧放置一个 Label
。
目前我正在使用 DockPanel
将 ListBox
停靠到窗口的右下角,但我不确定如何“分组”标签和 ListBox
在一起,以便它们保持在一起。
我是否必须通过硬编码两者的边距来完成此操作,以便它们看起来连接在一起?
另外我应该使用什么控件来做到这一点? StackPanel、DockPanel 等?
I have a ListBox
at the bottom right side of my window, and I want to place a Label
at the leftmost top side of this ListBox
.
Currently I am using a DockPanel
to dock the ListBox
to the bottom right side of the window, but I am not sure how to "group" the Label and the ListBox
together so they stay together.
Do I have to accomplish this with hardcoded margins for both so they appear they are attached together?
Also what control should I use to do this? StackPanel
, DockPanel
, etc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嵌套另一个 DockPanel。将您的标签作为第一个子项,并将其停靠在顶部。把你的ListBox作为第二个孩子;它将填充剩余的空间。
Nest another DockPanel. Put your Label as the first child, and dock it to top. Put your ListBox as the second child; it will fill the remaining space.
将两个控件放在单单元格
Grid
中,并设置每个控件的Margin
属性,以将它们绝对定位在单元格内。这将允许您将Grid
内的两个控件“粘合”在一起(您控制它们的大小和它们在单元格内的位置,因此粘合在一起),这将充当“石斑鱼”。然后,您可以使用任何您想要的方式(例如
DockPanel
)将网格放置在您喜欢的任何位置。内部的两个控件会移动,但始终保持在一起。如果您不需要像素完美的绝对定位,那么如果您使用 StackPanel 而不是 Grid,同样的技术也适用。在这种情况下,您将受到
StackPanel
可实现的布局的限制。Put both controls in a one-cell
Grid
, and set theMargin
property on each to position them absolutely within the cell. This will allow you to "glue" the two controls together (you control their size and their position within the cell, so glued) inside theGrid
, which will function as the "grouper".You can then use any way you want (e.g.
DockPanel
) to position the grid wherever you like. The two controls inside will move but always stay together.If you do not require pixel-perfect absolute positioning, the same technique will also work if you use a
StackPanel
instead of aGrid
. In this case, you will be limited by the layouts achievable with aStackPanel
.