简体   繁体   中英

How do I bind the height of a StackPanel to the height of the containing Grid in WPF?

Im relatively new to WPF so I'm sorry in advance if there is a simple solution to this. However, I am trying to bind the height of a StackPanel to its containing Grid. I understand that a StackPanel automatically resizes to fit its elements but I would like to bind it to the Grid so that it does not do this. Right now the stack panel does not resize with the window since it remains the size it needs to be in order to fit its elements.

Here is what I have so far:

<Grid x:Name="MainGrid" Grid.Row="2" Margin="1" Drop="Grid_Drop" 
      AllowDrop="True">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="175"/>
        <ColumnDefinition Width="5"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <StackPanel x:Name="SidePanel" Grid.Column="0" Height="{Binding 
                ActualHeight, ElementName=MainGrid, Mode=OneWay}">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition/>
            </Grid.RowDefinitions>
        <local:DeviceTreeView x:Name="deviceTree" PyngInfo="{Binding 
                              PyngSystemVm.PyngInfo}" Grid.Row="0"/>

    </StackPanel>

    <-- There is more code here but it is not important for answering this 
        question -->

</Grid>

I tried binding the height of "SidePanel" to the actual height of "MainGrid" but when I run this code and inspect the elements the Grid resizes with the window but the StackPanel does not. The StackPanel and the Grid even have different heights which doesn't make sense to me as their heights should be bound together.

I have also tried wrapping the entire StackPanel in a border and binding to that but that also did not work.

You don't need to bind the height of the StackPanel, simply setting its VerticalAlignment to Stretch will do it. However... You are still not going to get what I think you want. The StackPanel only stacks its child controls, it does not adjust them (at least not in the "stack" direction). Look into using a different control like Grid or UniformGrid or just expand your existing grid to have rows as well as columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM