Binding Dictionary to DataGrid (WPF)

I have multiple lists of objects of the same type that contain a dictionary property and I want to bind a datagrid column header to the key, and the cell values to the dictionary's value. Example of the object: public class MyObject { public Dictionary<string, string> Data { get; } // key would be a column header, value would be cell value } Now, in each list, the keys themselves will remain the same for each object's dictionary, but could change between lists, so I can't have static column headers. There is no editing in the grid, although I am gonna allow the hiding of columns and filtering. Not sure the best way to go about this. If it was static keys I could just create an object to represent the data in the dictionary and make an observable collection of that.
2 Replies
lycian
lycian•9mo ago
I don't know of a clever way to bind this other than just to have
AutoGenerateHeaders="false" attachedBehaviors:DataGridColumnsBehavior.BindableColumns=
"{Binding ColumnDefinitions}"
AutoGenerateHeaders="false" attachedBehaviors:DataGridColumnsBehavior.BindableColumns=
"{Binding ColumnDefinitions}"
and
c#
public ObservableCollection<DataGridColumn> ColumnDefinitions { get; } = new();
c#
public ObservableCollection<DataGridColumn> ColumnDefinitions { get; } = new();
then fill in with
c#
foreach (var key in Data.Keys)
{
ColumnDefinitions.Add(/*whatever kind of column*/);
}
c#
foreach (var key in Data.Keys)
{
ColumnDefinitions.Add(/*whatever kind of column*/);
}
Nacho Man Randy Cabbage
Nacho Man Randy CabbageOP•9mo ago
Thanks! yeah that's pretty much what I ended up doing. works fine 🙂
Want results from more Discord servers?
Add your server