Home WPF DataGrid custom header widths when auto-generated

# WPF DataGrid custom header widths when auto-generated

user7195
1#
user7195 Published in September 20, 2018, 4:35 pm

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<MyListObj> list where MyListObj has two string props "Name" and "Count".

If I try to define the columns in the XAML (<Grid.ColumnDefinitions>), 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?

• Not sure what your real problem is. But I have the feeling you have not set AutoGenerateColumns = false. Otherwise you get double the number of columns as you have properties. – gomi42 Feb 14 at 14:52
• I feel like a total idiot, but that was it. Thanks! – Eclectic Feb 15 at 15:35