拉伸空的 WPF ListView 以占用剩余空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2927785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stretch empty WPF ListView to take the remaining space
提问by TalkingCode
I always have problems with a ListView inside a dynamic layout control like a Stackpanel.
我总是在动态布局控件(如 Stackpanel)中遇到 ListView 问题。
Right now I have a Window with a Stackpanel as Root-Control. The Stackpanel streches perfectly and takes the complete window. Inside the StackPanel are some other controls like textboxes and button all aligned fine.
现在我有一个带有 Stackpanel 的窗口作为根控件。Stackpanel 完美地拉伸并占据完整的窗口。StackPanel 内部是一些其他控件,如文本框和按钮,它们都对齐良好。
The last Object is a ListView. I want the ListView to take the remaining space from the StackPanel but it does not. Even with VerticalAlignment="Stretch"I only get the column headers. The ListView only grows when items are added to it. So I have to set the ListView height manually.
最后一个对象是一个 ListView。我希望 ListView 从 StackPanel 中获取剩余空间,但它没有。即使使用VerticalAlignment="Stretch"我也只能得到列标题。ListView 仅在向其中添加项目时才会增长。所以我必须手动设置 ListView 高度。
How can I make the ListView fill the remaining space in a StackPanel even when it is empty?
即使 ListView 为空,如何让 ListView 填充 StackPanel 中的剩余空间?
回答by bitbonk
This has nothing to do with the ListView. It is the StackPanel's "fault". In a StackPanel the child items alwaysconsume only the space they need (in the direction of the orientation of the StackPanel). That's how the StackPanel is designed. Use a DockPanel instead, there you can make the last item fill up all the space that is left over using LastChildFill="true"
(true
is default, so no need to explicity specify it).
这与 ListView 无关。这是 StackPanel 的“错误”。在 StackPanel 中,子项总是只消耗它们需要的空间(在 StackPanel 的方向上)。这就是 StackPanel 的设计方式。改用 DockPanel,在那里您可以使用LastChildFill="true"
(true
是默认值,因此无需明确指定)使最后一个项目填满剩余的所有空间。
<DockPanel Background="Green">
<Button DockPanel.Dock="Top">Text</Button>
<ListView DockPanel.Dock="Top">
<ListView.View>
<GridView>
<GridViewColumn/>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
回答by Lee Treveil
How about using a grid? Grids are made for this kind of layout. The DockPanel is a good suggestion too.
使用网格怎么样?网格是为这种布局制作的。DockPanel 也是一个很好的建议。
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="row1"/>
<Button Grid.Row="1" Content="row2"/>
<ListView Grid.Row="2">
<ListViewItem Content="Text"/>
<ListViewItem Content="Text1"/>
<ListViewItem Content="Text2"/>
</ListView>
</Grid>
The important part is the Height="*", this tells the row to take up all available space, you can leave this out if you want as it is the default behaviour.
重要的部分是 Height="*",它告诉行占用所有可用空间,如果需要,您可以将其省略,因为它是默认行为。