让 ListBox 随窗口调整大小,但不随内容调整大小 [英] Get ListBox to resize with window, but not resize with content

查看:22
本文介绍了让 ListBox 随窗口调整大小,但不随内容调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题一定有一个优雅的解决方案,但我在网上找不到任何东西.我有一个网格,它有一列和一行的宽度/高度*,包含一个列表框.我将 Window SizeToContents 设置为 WidthAndHeight 以允许窗口调整为每组 UI 小部件/字体的适当大小.当我将项目添加到 ListBox 时,它会调整大小,导致窗口变大.

There must be an elegant solution to this problem, but I can't find anything online. I have a grid that has one column and row with width/height *, containing a ListBox. I have my Window SizeToContents set to WidthAndHeight to allow the window to resize to the proper size for each set of UI widgets/fonts. When I add items to the ListBox, it resizes, causing the window to grow.

如果我更改窗口的大小,我希望 ListBox 调整大小,但如果我添加的内容比 ListBox 的宽度长,我希望滚动条出现而不是让它增长,从而导致窗口生长.如果我为 Window 设置显式大小并将 SizeToContent 设置为 Manual(默认值),它会按我的意图工作.

I want the ListBox to resize if I change the size of the window, but if I add content that is longer than the width of the ListBox, I want the scrollbar to appear and not for it to grow, causing the Window to grow. If I set explicit sizes for the Window and set SizeToContent to Manual (the default), it works as I intend.

有没有办法在启动时根据内容调整窗口大小并继续让 ListBox 随窗口大小而不是其内容而增长?

Is there any way to size the window to the contents at startup and continue to have the ListBox grow with the window size, but not with its content?

推荐答案

按照 Potecaru Tudor 的建议,我通过将 ListBox 包装在另一个容器中并将 ListBox 的高度绑定到容器的 ActualHeight 解决了类似的问题.

Following Potecaru Tudor's suggestion, I solved a similar issue by wrapping the ListBox in another container and binding the ListBox's Height to the ActualHeight of the container.

这里有一个 XAML 代码片段来提供帮助:

Here is a XAML code snippet to help:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Border x:Name="HeightHelperPanel" Grid.Row="0">
        <ListBox ItemsSource="{Binding Path=FileNameCollection}"
                 MinHeight="60"
                 Height="{Binding Path=ActualHeight, ElementName=HeightHelperPanel}"/>
    </Border>
</Grid>

基本上,Border 容器在其内容增长时不会增长,但会一直拉伸到网格行的高度.网格行将填满包含窗口允许的任何空间,但不希望在窗口上强制任何高度限制.ListBox 的高度因此被限制为边框的高度.

Basically, the Border container doesn't grow when its content grows, but it will stay stretched to the height of the grid row. The grid row will fill up any space the containing window will allow it, but will not want to force any height constraints on the window. The ListBox's height is therefore constrained to the height of the Border.

希望对遇到这个令人沮丧的问题的其他人有所帮助.

Hope that helps anyone else who has had this somewhat frustrating issue.

这篇关于让 ListBox 随窗口调整大小,但不随内容调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆