简体   繁体   中英

WPF grid layout and how to deal with too narow window

I'd like to have a WPF panel with two columns, where the 2nd one is fixed width and is to the right of the first column. The first columns is auto-sized. I want the second column to always be right after the first one, but also not to get lost when window (or parent element) gets too narrow and only first column or a part of the first column fits.

When I use DockPanel like this:

<DockPanel DockPanel.Dock="Top">
  <Label Content="I am autosize" DockPanel.Dock="Left" />
  <Label Content="I come right after the first column" />
</DockPanel>

The first column is visible, the second is right after it and when I start to resize the window to make it more narrow, firstly, the second column gets cropped until it disappers, the the first one is cropped.

When I use this:

<DockPanel DockPanel.Dock="Top">
  <Label Content="I come right after the first column" DockPanel.Dock="Right" />
  <Label Content="I am autosize" />
</DockPanel>

The second column start to be cropped second, but when window is wide enough, it is not right after fill-docked first one, it is docked to the right. The first column is not auto-sized.

When I tried to use the Grid, result were basically the same. When I set column widths to *, 20, *, it doesn't work, *, 20, Auto also doesn't make it behave exactly the way I want.

Is it even possible to use some Panel (DockPanel, prefferably) and layouting properties combination to make my second column appear always immediately to the right of the first one, but also make the first one crop first when both of their widths combined are larger than parent element width, so the second column in this case appears to be right-docked and the first one full-docked?

Thanks!

You can try to use the Grid control.

<Window x:Class="WpfApplication6.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" 
    MinWidth="200">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition  MinWidth="200"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="I am autosize" 
                   Background="Red" />
    <TextBlock Text="I come right after the first column" 
                   Grid.Column="1" 
                   Background="AliceBlue" 
                   Width="200" 
                   HorizontalAlignment="Left" />
</Grid>

The only problem is that you have to set also the parent control MinWidth to a fix size, in this example case, the window. I hope this can help you.

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