wpfdatagridcolumn-widthautogeneratecolumn

set max display width for a column in WPF datagrid


I have a datagrid in WPF that generate the columns automatically. some columns have a width more than whole screen, I want to check the width and if it is more than 500 then set it to 500 but if it is less than 500 keep the current width.

       <DataGrid x:Name="dgLM" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding}" HorizontalAlignment="Stretch" 
              Margin="5" VerticalAlignment="Stretch" IsReadOnly="True" CanUserAddRows="False" AutoGenerateColumns="True" CanUserDeleteRows="False"
              LoadingRow="dg_LoadingRow" AlternatingRowBackground="#FFDAD5D5" 
                AutoGeneratingColumn="dgMain_AutoGeneratingColumn" >
            <!--<DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DarkGray"/>
        </DataGrid.Resources>-->
            <DataGrid.Resources>
                <Style TargetType="{x:Type DataGridCell}">
                    <Style.Triggers>
                        <Trigger Property="DataGridCell.IsSelected" Value="True">
                            <Setter Property="Background" Value="DarkGray" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
        </DataGrid>

and the code is:

    private void dgMain_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(System.DateTime))
            (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy HH:mm:ss";

        //e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
        if (e.Column.Width > 500)
        {
            e.Column.Width = 500;
        }

    }

appreciate any help!


Solution

  • When dealing with Column width in AutoGeneratingColumn you should use DataGridLength.

    You can also change e.Column.MaxWidth that is a double instead.