Search code examples
wpfxamllayout

Make grid columns adjust width properly to content


I need 3 columns:

  • Label with variable width
  • Label with even more variable width (needs to be truncated)
  • Icon, fix size

What I have so far is:

<Grid SnapsToDevicePixels="True">
    <Grid.ColumnDefinitions>
        <!-- I tried 'Width' instead of 'MaxWidth'. No difference -->
        <ColumnDefinition MaxWidth="80" SharedSizeGroup="Label" />
        <ColumnDefinition Width="*" SharedSizeGroup="Name" />
        <ColumnDefinition Width="Auto" SharedSizeGroup="Icon" />
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Column="0"
               Text="{Binding Label}" 
               FontWeight="Bold"
               TextTrimming="CharacterEllipsis"
               TextWrapping="NoWrap" />
        <!-- Started with a simple TextBlock, tried StackPanel, now Grid.
            Still this one pushes the icon to the right -->
    <Grid Grid.Column="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0"
                   Text="{Binding Name}"
                   FontWeight="Bold" />
        <TextBlock Grid.Column="1"
                   Text="{Binding CombinedDisplayName}"
                   TextTrimming="CharacterEllipsis"
                   TextWrapping="NoWrap" />
    </Grid>
    <materialDesign:PackIcon Grid.Column="2"
                             HorizontalAlignment="Right"
                             Kind="ConsoleNetworkOutline" />
</Grid>

What I want is:

  • The first column should take the space it needs
  • The third column is fixed and always maximum to the right (the parent grid changes the size)
  • The second column should have the rest of the space and the text should be truncated if needed

I also tried to give this parent Grid a fixed size. Still it will only work if I give hardcoded sizes to the TextBlocks.

Edit:

A bad side-effect right now is: When the center part is too small it "pulls" the right column. But the right column should stay to the most right all the time and the center should just take up the whole space.


Solution

  • Oof, as usual, once you post the question, you get it yourself:

    The SharedSizeGroup on the middle Width=* column messed me up. Now I have:

    <Grid.ColumnDefinitions> </Grid.ColumnDefinitions>

    And this way the first column depends on the length of the text, the third column is on the far right and the middle one takes all the other space and truncates the string there.

    So resizing the parent view works and all the space is used nicely.