Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my Grid Columns always be the same width?

Tags:

wpf

xaml

grid

If I set the Column's width to *, they're the same width initially but if an item is larger than the amount allowed then it will stretch the column width.

How can I force my Grid to keep it's columns the same size with explicitly defining a size?

I cannot use a UniformGrid because this Grid is being used in an ItemsControl, and the Items need to be placed in specific Grid.Row/Grid.Column spots

Edit Here's a sample of my current code.

<DockPanel>

    <!-- Not showing code here for simplicity -->
    <local:ColumnHeaderControl DockPanel.Dock="Top" />
    <local:RowHeaderControl DockPanel.Dock="Left" />

    <ItemsControl ItemsSource="{Binding Events}">
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="Grid.Column" 
                        Value="{Binding DueDate.DayOfWeek, 
                            Converter={StaticResource EnumToIntConverter}}" />
            </Style>
        </ItemsControl.ItemContainerStyle>

        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </ItemsPanel>
    </ItemsControl>

</DockPanel>

Edit #2 Here's my final solution. It makes the columns the correct size, and it keeps the size correct when the application gets resized.

<ColumnDefinition Width="{Binding 
    ElementName=RootControl, 
    Path=ActualWidth, 
    Converter={StaticResource MathConverter}, 
    ConverterParameter=(@VALUE-150)/7}" />

150 is the width of the Row Headers + all margins and borders. I'm actually in the process of updating my MathConverter to an IMultiValueConverter so I can bind both parameters (If you're interested in the Converter code it can be found here, although it's only the single-value converter)

like image 734
Rachel Avatar asked Sep 26 '11 17:09

Rachel


1 Answers

You could:

1) Hardcode a size in DIP:

<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
...

2) Use SharedSizeGroup, it takes a char

<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition SharedSizeGroup="A" />
...

You can read more about it here

like image 71
Louis Kottmann Avatar answered Oct 21 '22 08:10

Louis Kottmann