Wpf size control for content?

How to get a WPF control to resize to fit its contents?

+54
wpf wpf-controls autosize
Nov 17 '09 at 3:39
source share
4 answers

For most controls, you set the height and width to Auto in XAML, and the size will match its contents.

In the code, you set the width / height to double.NaN . See FrameworkElement.Width for more information, in particular the Remarks section.

+71
Nov 17 '09 at 3:42
source share

I had such a problem when I indicated the width of my window, but had a height equal to Auto . The DockPanel child set its VerticalAlignment to "Top", and the window was set to "Vertical match" for the Version, but the Window will still be much higher than the contents.

Using Snoop, I found that the ContentPresenter inside the Window (part of the window, and not what I put there) has a VerticalAlignment set to Stretch and cannot be changed without having to re-view the entire window

After many disappointments, I discovered the SizeToContent property - you can use this to indicate whether you want the Window to be sized vertically, horizontally or both, depending on the size of the content - now everything looks beautiful, I just can't believe it that it took me so long to find this property!

+26
Feb 23 '10 at 12:07
source share

If you use a grid or similar component: In XAML, make sure that Grid.Row and Grid.Column are defined in the grid elements, and make sure that they have no fields. If you used designer mode or Expression Blend mode, it could assign fields to the entire grid, and not to specific cells. As for the size of the cell, I add an extra cell that fills the rest of the space:

  <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*"/> </Grid.RowDefinitions> 
+1
Jan 13 '12 at 15:06
source share

I had a user control that sat on the page in a free form, and was not limited to another container, and the content in the user element was not automatically changed, but expanded to the full size of what was transferred by the user.

So that the user control could just size its contents, only for height, I placed it in a grid with a row set to auto-size, for example:

 <Grid Margin="0,60,10,200"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <controls1:HelpPanel x:Name="HelpInfoPanel" Visibility="Visible" Width="570" HorizontalAlignment="Right" ItemsSource="{Binding HelpItems}" Background="#FF313131" /> </Grid> 
+1
Aug 25 '15 at 14:40
source share



All Articles