简体   繁体   中英

WPF Grids - how to maintain column width when window is resized?

I have this XAML markup...

<Grid Name="ProductsGrid" Width="500">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="ProductList" Width="*" />
            <ColumnDefinition Name="ProductInfo" Width="100" MinWidth="10" MaxWidth="100"/>
        </Grid.ColumnDefinitions>

When the app starts the 2nd column is se to 100 "units" wide.

When the window is resized the column grows and shrinks - it maintains its ratio with column 1 which I think is what i supposed to happen in WPF. So when the app starts the window size is set to 500 and the 2nd column is 1/5 of the total width. As the app resizes it maintains 1/5 of the total width However in this example I want it to stay at 100 units.

Any ideas?

Remove the width of the grid, it is fixing the width of the grid, the grid remains 100 in width ... give the grid background color if you want to see the actual grid location.

you can fix the initial width of the main window to 100 and leave the grid without fixed width to allow the desired behavior

try this:

<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"  Width="100" x:Name="MyWindow">
    <Grid Name="ProductsGrid">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Name="ProductList" Width="*" />
                <ColumnDefinition Name="ProductInfo" Width="100" MinWidth="10" MaxWidth="100"/>
            </Grid.ColumnDefinitions>

Try this

<Grid Name="ProductsGrid"  ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="ProductList" Width="*" />
            <ColumnDefinition Name="ProductInfo" Width="100" MinWidth="10" MaxWidth="100"/>
        </Grid.ColumnDefinitions>
    </Grid>

You need to remove the fixed width of Grid.

If you want your initial window to be of size 500 then you can handle window loaded event and set the size of window to 500. Don't hard code size of Grid in code behind or XAML otherwise you will face same issue again

 private void mywindow_Loaded(object sender, RoutedEventArgs e)
            {
                this.Width = 500;
            }

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