Home WPF DataGrid custom header widths when auto-generated

# WPF DataGrid custom header widths when auto-generated

Eclectic
1#
Eclectic Published in 2018-02-14 11:56:00Z
 I am a WPF newb But I have some development chops. I have tried many options to get this to work but am stumped... I would like a simple DataGrid of two Columns; "Name" and "Count". I would like "Name" to be width * (remaining available) and "Count" to be width 50 locked to the right edge. I would like this as the Grid cell this DataGrid control resides in is resizable (The DataGrid has both Horizontal and Vertical Alignment set to "Stretch"). On Grid cell resize, I would like for the "Name" column on the left to expand or contract to fill the available space left by the 50 wide "Count" column on the right. The DataGrid is populated via ItemSource with a custom SortableBindingList list where MyListObj has two string props "Name" and "Count". If I try to define the columns in the XAML (), I end up with FOUR columns when I set the ItemSource. I have tried Resources, Styles and Templates in the XAML (various answers and examples for similar issues found here, codeproject and MSDN) and explicitly setting the values in code. The closest I have gotten is setting in code when DataGrid is Loaded: MyDataGrid.Loaded += (s, o) => { if (MyDataGrid.Columns.Count() == 2) { MyDataGrid.Columns[0].Width = new DataGridLength(1,DataGridLengthUnitType.Star); MyDataGrid.Columns[1].Width = 50; } };  In this case, I get my left resizing "Name" column and my right "Count" column locked and fixed, but I also get a 50px space between the two columns (a phantom 3rd column? I have no idea where that is coming from!). If I set the headers and data in the XAML, it is super easy, but of course, the data is dynamic and set via ItemSource, so is not an option in this case. Or is it somehow? This one is driving me nuts! Any ideas?
mm8
2#
 Handle the AutoGeneratedColumns event: private void dg_AutoGeneratedColumns(object sender, EventArgs e) { dg.Columns[0].Width = new DataGridLength(1, DataGridLengthUnitType.Star); dg.Columns[1].Width = new DataGridLength(50, DataGridLengthUnitType.Pixel); }  XAML:   Or set the AutoGenerateColumns property of the DataGrid to false and define your columns explicitly in your XAML markup.