Home > Blockchain >  DockPanel resize objects inside
DockPanel resize objects inside

Time:06-08

I want to make my objects in DockPanel expand automatically when the window is resized, currently they only change their position.

My XAML:

<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Width="405">
        <Image Source="/myImage.png"></Image>
    </ScrollViewer>
    <Button Width="406"/>
</DockPanel>

CodePudding user response:

The DockPanel is primarily intended to position elements relative to each other, but it does not distribute the available space with special constraints for each child proportionally.

The SetDock method changes the position of an element relative to other elements within the same container. Alignment properties, such as HorizontalAlignment, change the position of an element relative to its parent element.

It only allows you to let the last child added to take any remaining space.

If you set the LastChildFill property to true, which is the default setting, the last child element of a DockPanel always fills the remaining space, regardless of any other dock value that you set on the last child element.

That means you could let your ScrollViewer stretch, but not the Button and vice-versa. To do this, make the control that should take the remaining space the last one in the DockPanel, e.g.:

<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
   <Button Width="406" DockPanel.Dock="Right"/>
   <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
      <Image Source="/myImage.png"/>
   </ScrollViewer>
</DockPanel>

The default value of LastChildFill is true, so you do not have to specify it explicitly.


A different approach to fulfill your requirements is to use a Grid instead. A Grid can take proportional sizing constraints (star * sizing) for any row and column.

Columns and rows that are defined within a Grid can take advantage of Star sizing to distribute remaining space proportionally. When Star is selected as the height or width of a row or column, that column or row receives a weighted proportion of the remaining available space. This is in contrast to Auto, which distributes space evenly based on the size of the content that is within a column or row.

This allows you to specify precisely how the available space is distributed.

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="405*"/>
      <ColumnDefinition Width="406*"/>
   </Grid.ColumnDefinitions>
   <ScrollViewer Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
      <Image Source="/myImage.png"/>
   </ScrollViewer>
   <Button Grid.Column="1"/>
</Grid>
  • Related