Install WPF control to expand available space and no more

How can I configure a WPF control to fill the available space in the parent container but not extend the parent?

The following snippet describes the layout I am trying to execute. I would like the Grid stretch to accommodate the Expander , and I would like the ListBox populate the Grid . I want the ListBox scroll bar to appear when the Grid too small to show all ListBoxItem s.

 <ScrollViewer> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <ListBox Grid.Row="0" Grid.Column="0" /> <Expander Grid.Row="0" Grid.Column="1" Header="Expander" /> </Grid> </ScrollViewer> 

What is currently happening is that the Grid stretched to fit all the ListBox , and the outer row of the ScrollViewer vertical scrollbar appears. I want the outer scrollbar to appear when the Expander gets too big to fit on the screen.

+2
height scroll wpf autosize
source share
2 answers

To solve the same problem, I wrote a special container class:

 class FrugalContainer : Decorator { protected override Size MeasureOverride(Size availableSize) { return new Size(0, 0); } protected override Size ArrangeOverride(Size arrangeSize) { // get it all Child.Measure(arrangeSize); Child.Arrange(new Rect(arrangeSize)); return Child.RenderSize; } } 

Surround your ListBox with a container, and the height of the ListBox will be the same as Expander.

 <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <FrugalContainer Grid.Row="0" Grid.Column="0" > <ListBox /> </FrugalContainer> <Expander Grid.Row="0" Grid.Column="1" Header="Expander" /> </Grid> 

Note that I am removing Width="Auto" from the column definition because the FrugalContainer will be as small as possible. Therefore, you cannot set the width or height of the parent grid cell to Auto.

If you need automation, rewrite the container:

 class FrugalHeightContainer : Decorator { protected override Size MeasureOverride(Size availableSize) { Child.Measure(availableSize); return new Size(Child.DesiredSize.Width, 0); } protected override Size ArrangeOverride(Size arrangeSize) { Child.Measure(arrangeSize); Child.Arrange(new Rect(arrangeSize)); return Child.RenderSize; } } 
+3
source share

What is the meaning of ScrollViewer ? Just let ScrollViewer in the ListBox template naturally when too little space is available.

 <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <ListBox Grid.Row="0" Grid.Column="0" /> <Expander Grid.Row="0" Grid.Column="1" Header="Expander" /> </Grid> 
0
source share

All Articles