【问题标题】:ListBox or other Items Control in a ScrollViewerScrollViewer 中的 ListBox 或其他项控件
【发布时间】:2011-03-22 14:20:06
【问题描述】:

我们有一个包含各种元素和数据网格的表单。当列表框包含在滚动查看器中时,当我们增加窗口大小时,一切都很好。当窗口大小减小时,列表框的高度保持不变,垂直滚动条变为活动状态。如果您摆脱列表框上的高度绑定,列表框将达到其最大所需高度。如果我们根本没有列表框,那么边框的行为就像我们想要的那样。

我们可以使用下面的代码来模拟我们的问题。

<Window
   x:Class="WpfApplication1.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="MainWindow"
   Height="150"
   Width="525">

   <Grid
      Margin="10">

      <ScrollViewer>
         <Grid>
            <Grid.RowDefinitions>
               <RowDefinition
                  Height="*" />
               <RowDefinition
                  Height="Auto" />
            </Grid.RowDefinitions>

            <Border
               x:Name="border"
               MinHeight="40" />

            <ListBox
               Height="{Binding ElementName=border, Path=ActualHeight}">
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
               <ListBoxItem>Item 1</ListBoxItem>
            </ListBox>

            <ToolBar
               Grid.Row="1">
               <Button
                  Content="Add" />
            </ToolBar>
         </Grid>

      </ScrollViewer>
   </Grid>
</Window>

我们如何让 ListBox 像没有 ListBox 时一样调整边框的大小?

【问题讨论】:

    标签: wpf listbox scrollviewer


    【解决方案1】:

    我不确定您要在这里做什么,但是如果您希望列表框在窗口高度降低时降低它的高度,那么您必须在边框上添加边距,就像

            <Border
               Margin="5"
               x:Name="border"
               MinHeight="40" />
    

    注意:

    这会降低列表框的高度,但它可能会激活列表框的内部滚动,因此您会在那里看到两个滚动条。

    另一方面,您还可以删除第一个行定义的 height="*",这样它就可以保留其余的网格高度。

    【讨论】:

    • 即使边距设置为 0.1,此解决方案也有效。你有解释为什么会这样吗?
    • err,我真的很抱歉,但我也不知道它在你的情况下是如何工作的。当我试图阻止文本框增长时,即使没有设置宽度,这是我在网上发现的一个技巧。试图再次找到链接,它似乎也来自这个网站哈哈stackoverflow.com/questions/386039
    【解决方案2】:

    不是 100% 确定您在寻找什么,但我认为

    <ListBox HorizontalAlignment="Stretch"
             VerticalAlignment="Stretch">
    

    可能是你需要的。它会缩小列表框,直到达到最小尺寸(以显示所有项目),然后激活滚动条。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2011-04-17
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多