如何兼顾Expander自适应布局与ListView超出窗口时的滚动条?
解决方案
1. 保留原有布局的折叠特性
窗口中的Grid行定义继续使用Height="Auto",确保折叠的Expander不占用多余空间:
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Expander Grid.Row="0" VerticalAlignment="Top"> <local:ListView1 DataContext="{Binding Source1}"/> </Expander> <Expander Grid.Row="1" VerticalAlignment="Top"> <local:ListView1 DataContext="{Binding Source2}"/> </Expander> <Expander Grid.Row="2" VerticalAlignment="Top"> <local:ListView1 DataContext="{Binding Source3}"/> </Expander> </Grid>
2. 修改ListView1用户控件,添加高度约束与滚动支持
给ListView设置最大高度限制,绑定到窗口的实际高度(通过转换器扣除标题栏、边框等额外高度),同时确保滚动条自动触发:
<Grid> <ListView ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Auto" MaxHeight="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualHeight, Converter={StaticResource WindowHeightConverter}}"> <!-- ListView的列定义与内容 --> </ListView> </Grid>
3. 实现窗口高度转换器
创建一个转换器类,用于调整窗口高度,避免ListView超出窗口范围:
using System; using System.Globalization; using System.Windows.Data; namespace YourProjectNamespace { public class WindowHeightConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is double windowHeight) { // 根据实际窗口样式调整扣除值,默认70适配标准窗口标题栏+边距 return windowHeight - 70; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
4. 在窗口资源中注册转换器
<Window x:Class="YourProjectNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:YourProjectNamespace" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <local:WindowHeightConverter x:Key="WindowHeightConverter"/> </Window.Resources> <!-- 窗口布局内容 --> </Window>
效果说明
- 折叠Expander时,对应Grid行高度自动收缩为0,不占用空白空间;
- 展开Expander时,ListView的最大高度被限制在窗口可用范围内,内容超出时自动显示垂直滚动条;
- 适配不同窗口大小,无需手动调整固定高度。
内容的提问来源于stack exchange,提问作者Jtastic
相关产品推荐
相关产品推荐

