views:

1268

answers:

2

How do I make a WPF control to change its size according the content in it?

+5  A: 

For most controls, you set it's 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.

Reed Copsey
In addition a lot of controls set their Horizontal- and VerticalAlignment to Stretch which will cause them to fill an available area so you will probably need to specify these properties, e.g. HorizontalAlignment="Left" VerticalAlignment="Top".
Bryan Anderson
+2  A: 

I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto. The child DockPanel had it's VerticalAlignment 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's VerticalAlignment set to Stretch 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!

TabbyCool
I wish all the Grids would have this property...
Shimmy
When the problem applies to the top level window Set SizeToContent="WidthAndHeight". I lost hours on this one - it's not intuitive! See http://stackoverflow.com/questions/812079/window-heightauto-problem
DeveloperDan