0
votes

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?

1
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
I feel like a total idiot, but that was it. Thanks!Eclectic

1 Answers

2
votes

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:

<DataGrid x:Name="dg" AutoGeneratedColumns="dg_AutoGeneratedColumns" />

Or set the AutoGenerateColumns property of the DataGrid to false and define your columns explicitly in your XAML markup.

<DataGrid x:Name="dg" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" Width="*" />
        <DataGridTextColumn Binding="{Binding Count}" Width="50" />
    </DataGrid.Columns>
</DataGrid>