How do I make a WPF control to change its size according the content in it?
相关问题
- VNC control for WPF application
- WPF Binding from System.Windows.SystemParameters.P
- XAML: Applying styles to nested controls
- How can I add a horizontal line (“goal line”) for
- How to properly change a resource dictionary
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:
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:
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!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.