Silverlight:延伸到StackPanel中的剩余空间

Ran*_*oet 39 silverlight stackpanel

我有一个带有两个元素的垂直StackPanel:一个Button和一个ListBox.如何将ListBox拉伸到剩余的页面高度?

<StackPanel Height="Auto" Width="Auto">
    <Button Height="30" Width="100" Content="Get Content" x:Name="GetContent"/>
    <ListBox Height="Auto" Width="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

请注意,我使用Grid容器使其工作:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Width="100" Height="30" Content="Get Content" Click="OnGetContent" Grid.Row="0" Grid.Column="0"/>
    <data:DataGrid x:Name="MyContent" Margin="0,5" Grid.Row="1" Grid.Column="0"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

Jam*_*add 40

好吧,您已经找到了解决方案;)StackPanels默认不会填充任何剩余空间,因为它们的大小总是等于其子元素的组合所需大小.Grid是一个很好的方法,因为它会在浏览器大小更改时动态调整大小.Mark的使用DockPanel的答案也很好.唯一的另一种方法是在父控件的大小更改时手动调整元素的大小.一般来说,坚持外部布局的网格,他们用StackPanels和其他控件填充它们,你应该设置.


Mar*_*ath 20

你可以使用DockPanel.将第一个项目设置为停靠顶部,将第二个项目设置为停靠填充,或使用LastChildFill属性:

<toolkit:DockPanel LastChildFill="True"
 xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">    
    <Button DockPanel.Dock="Top" Height="30" Width="100" 
     Content="Get Content" x:Name="GetContent"/>
    <ListBox Background="Azure" />
</toolkit:DockPanel>
Run Code Online (Sandbox Code Playgroud)


小智 15

我同意詹姆斯的观察,即"StackPanels默认不填充任何剩余空间,因为它们的大小总是等于其子元素的合并所需大小." 这正是发生的事情,但这不是预期的结果.

我可以看到为什么这条指令会将内容压缩到最小的必要空间.

<StackPanel Height="Auto" Width="Auto">
Run Code Online (Sandbox Code Playgroud)

但是... StackPanel接受一个Horizo​​ntalAlignment参数 - 如果选中该参数,则应该使堆栈面板填充其父容器的内容.这正是您设置Orientation ="Vertical"时发生的情况.请注意,在这种情况下,StackPanel将确定可用的水平空间量并将其分配给子控件.

<StackPanel Height="30" Orientation="Vertical" HorizontalAlignment="Stretch" > 
   <TextBox /> <!--TextBox fills entire space-->
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

只有在Orientation ="Horizo​​ntal"时,水平子尺寸才会出现故障.

<StackPanel Height="30" Orientation="Horizontal" HorizontalAlignment="Stretch" > 
   <TextBox /> <!--TextBox fills smallest space available-->
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

  • 我刚碰到这个...它似乎比任何东西都更像一个bug. (3认同)
  • 我现在也在努力解决这个问题(虽然我正在使用WPF).在StackPanel上设置Orientation ="Horizo​​ntal"会以某种方式阻止它使用Horizo​​ntalAlignment ="Stretch"进行拉伸. (2认同)