简体   繁体   中英

Prevent WPF Datagrid column resize

The Datagrid with read only column gets resized when data field it is bind to changes.

Initially it gets displayed with width of around 100px but due to change in external data source causes it to get resize to 150px.

Even though the data displayed inside the column gets changed i want to make sure the data column width does not change.

Setting MaxWidth fixes this problem, but it prevents user from manually resizing the column, which is not acceptable.

You can use the AutoGeneratingColumn event and handle the width in there.

In XAML:

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>

In code behind:

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Width = new DataGridLength(100);
}

This would essentially limit column size when they are being generated but still allow the user to re size them once they are loaded.

If you don't generate the columns automatically like in kyriacos_k answere, you can simply set the width of the column and the CanUserResizeColumns property of the datagrid itself:

<DataGrid ItemsSource="{Binding YourSource}" 
                      CanUserResizeColumns="True"
                      EnableRowVirtualization="True">
    <DataGrid.Columns>
        <DataGridTextColumn Width="100" Header="CustomHeader" Binding="{Binding YourProperty, Mode=OneWay}"  />
    <DataGrid.Columns>
</DataGrid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM