Search code examples
wpfgrid-layoutcolumn-width

WPF grid column 50% width


I need 3 columns in my Grid Layout, while looking like this:

  1. 50% of the window
  2. rest of the place
  3. 30px wide

But I am unable to set this up, do any of you have idea ho to achieve this?

I tryed to toy with the *, but it always parse the width without the column with fixed width and it does not looks good.

So this does not achieve what I need:

               <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="30"/>
            </Grid.ColumnDefinitions>

Thank you for help, David.


Solution

  • I would create Grid with two columns and in the second column another Grid.

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="30"/>
            </Grid.ColumnDefinitions>
        </Grid>
    </Grid>
    

    Another option is to handle SizeChanged event of Window and calculate the width of the first column.

    <Grid x:Name="MyGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="30"/>
        </Grid.ColumnDefinitions>
    </Grid>
    

    Code behind

    private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        MyGrid.ColumnDefinitions[0].Width = new GridLength(e.NewSize.Width / 2);            
    }