问题
I want a layout where a ListBox is placed at the top of the window and a button is attached to the bottom of the ListBox. When the window is too small I want the ListBox to scroll and the button to be visible. When the window is too large, i.e. enough space for all controls and all list items, I want the ListBox to take up exactly as much space as it needs, and empty space be added below the button.
I have tried DockPanel:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="200" Width="525">
<DockPanel LastChildFill="False">
<ListBox Name="List" DockPanel.Dock="Top">
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
</ListBox>
<Button Content="Button" DockPanel.Dock="Top"></Button>
</DockPanel>
</Window>
But then the button is not visible when the window is too small.
I have tried Grid:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="200" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<ListBox Name="List" Grid.Row="0">
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
<ListBoxItem>Item</ListBoxItem>
</ListBox>
<Button Content="Button" Grid.Row="1"></Button>
</Grid>
</Window>
But when the window is larger than needed, the ListBox is stretched larger than its content instead of empty space being added below the button.
If I change the RowDefinitions to:
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
Then the Listbox does not scroll when the window is too small.
Any ideas?
回答1:
try change Grid.VerticalAlignment. If it is set to Stretch (default value) and the window is larger than needed, the ListBox is also stretched because of Height="*"
.
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
来源:https://stackoverflow.com/questions/40460366/how-to-layout-scrolling-listbox-with-auto-max-height-and-attach-always-visible-b