Wpf控制内容大小?
如何使WPF控件根据其中的内容改变其大小?
How do I make a WPF control to change its size according the content in it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使WPF控件根据其中的内容改变其大小?
How do I make a WPF control to change its size according the content in it?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
对于大多数控件,您可以在 XAML 中将其高度和宽度设置为
Auto
,并且它将调整大小以适合其内容。在代码中,您将宽度/高度设置为 double.NaN。有关详细信息,请参阅 FrameworkElement.Width,特别是“备注”部分。
For most controls, you set its height and width to
Auto
in the XAML, and it will size to fit its content.In code, you set the width/height to
double.NaN
. For details, see FrameworkElement.Width, particularly the "remarks" section.我遇到了这样的问题,我指定了窗口的宽度,但将高度设置为
Auto
。子DockPanel
将其VerticalAlignment
设置为 Top,而 Window 将其 VerticalContentAlignment 设置为 Top,但 Window 仍然比内容高得多。使用 Snoop,我发现窗口内的
ContentPresenter
(窗口的一部分,不是我放在那里的东西)的VerticalAlignment
设置为Stretch
并且在不重新模板化整个窗口的情况下无法更改!经过一番挫折后,我发现了
SizeToContent
属性 - 您可以使用它来指定是否希望窗口根据内容的大小垂直、水平或水平调整大小 - 一切都调整得很好现在,我简直不敢相信我花了这么长时间才找到那处房产!I had a problem like this whereby I had specified the width of my Window, but had the height set to
Auto
. The childDockPanel
had it'sVerticalAlignment
set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.Using Snoop, I discovered that the
ContentPresenter
within the Window (part of the Window, not something I had put there) has it'sVerticalAlignment
set toStretch
and can't be changed without retemplating the entire Window!After a lot of frustration, I discovered the
SizeToContent
property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!我有一个用户控件,它以自由形式位于页面上,不受另一个容器的约束,并且用户控件中的内容不会自动调整大小,而是扩展到用户控件所传递的完整大小。
为了让用户控件简单地调整其内容的大小(仅针对高度),我将其放入网格中,并将行设置为自动调整大小,如下所示:
I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.
To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:
如果您使用网格或类似组件:
在 XAML 中,确保网格中的元素定义了 Grid.Row 和 Grid.Column,并确保它们没有边距。如果您使用设计器模式或 Expression Blend,它可能会分配相对于整个网格而不是特定单元格的边距。
至于单元格大小,我添加了一个额外的单元格来填充剩余的空间:
If you are using the grid or alike component:
In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells.
As for cell sizing, I add an extra cell that fills up the rest of the space: