Question

I have a case where I have to show data in Datagrid. Cols of DataGrid may vary from 2 to 20, I add cols dynamically. I just want to set the width of cols to "*" and make it utilize all available space on the screen. But as I am adding cols dynamically, I can't assign "" to the width in code. I tried with Auto, but no difference. What can be done to achieve the goal ? My XML :

           <DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch"  Margin="20,0,0,0"  x:Name="outputGrid" VerticalAlignment="Top"  HorizontalScrollBarVisibility="Visible"
                VerticalScrollBarVisibility="Visible" BorderBrush="#FFB7B39D" Background="LightYellow" RowBackground="LightGray" AlternatingRowBackground="#FFFFFFF5" BorderThickness="2" 
                CanUserReorderColumns="False" CanUserSortColumns="False" FontSize="13" MinWidth="675"
                IsReadOnly="True" ColumnWidth="*"
                ColumnHeaderStyle="{DynamicResource ColumnHeaderStyle}" ClipboardCopyMode="IncludeHeader" Foreground="Black"    >
                <DataGrid.RowHeaderStyle>
                    <Style TargetType="DataGridRowHeader">
                        <Setter Property="Content" Value="{Binding Title}" />
                    </Style>
                </DataGrid.RowHeaderStyle>

            </DataGrid>

Code that adds cols :

            foreach (Step2Model sm in xlsImpExp.Step2InfoDataModel.Step2ModelList)
        {
            DataGridTextColumn column = new DataGridTextColumn();
            column.Header = sm.LayerName;
            column.Width = DataGridLength.Auto;
            column.Binding = new Binding("Lay" + i + "Vol");
            outputGrid.Columns.Add(column);
            i++;
        }

How do I make sure that it utilize all space that is free on right side of the screen ? I searched a lot on this problem, but couldn't find any solution. Any help is highly appreciated.

Thanks

Was it helpful?

Solution

Set the width of the column this way:

column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

The "1" of course defines the relative width compared to the other columns. Just like in XAML 1*.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top