You can bind to your Columns collection in XAML but it is not so easy. And you need to have fixed index numbers in the Columns collection.
This is a starting point for what you can do in the code-behind instead.
This is the saving part in the Closing event handler:
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//Extract the properties for each column into the Columns collection
Columns.Clear();
foreach (DataGridColumn col in DataGrid.Columns)
{
Columns.Add(new MyDataGridColumn()
{
Text = col.Header?.ToString(),
Width=col.Width
//...
});
}
}
Revert the action in the Loading event to set the values.
You may need a little more advanced code to find the correct column. Here I have hardcoded to the first column.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
foreach (MyDataGridColumn col in Columns)
{
DataGrid.Columns[0].Header = col.Text;
DataGrid.Columns[0].Width = col.Width;
//..
}
}
Some observations:
Your name of class DataGridColumn conflict with the DataGrid's DataGridColumn. I have renamed your class to "MyDataGridColumn" above.
The DataGridColumn property Width is of type DataGridLength.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…