C# WPF - create columns from dictionary keys and bind column values to dictionary values

176 views Asked by At

My ViewModel contains

public ObservableCollection<MyResultRowsViewModels> ResultRows {get;set;}
public ObservableCollection<string> MyDictionaryKeys => ResultRows.SelectMany(x=>x.MyDictionary.Select(y=>y.Keys)).ToObservableCollection();

Where MyResultRowsViewModels, ItemSource of RadGridView, contains

Dictionary<string, decimal> MyDictionary {get;set;}

In xaml.cs file I am trying to generate columns with headers from MyDictionaryKeys with values from MyDictionary[MyDictionaryKey]

public void OnGetData(object sender, EventArgs eventArgs)
{
    var myKeys = ViewModel.MyDictionaryKeys;
    foreach (var name in myKeys)
    {
        MyRadGridView.Columns.Add(new GridViewDataColumn()
                                                         {
                                                             Header = name,
                                                             IsReadOnly = true,
                                                            DataMemberBinding  = new Binding($"MyDictionary[\"{name}\"]");
                                                         });
    }
}

As far as I understand, it's not working because MyDictionary[name] is not a property. So is there any way to bind column to dictionary value or any workaround?

I've tried something like this in MyResultRows

public string CurrentlyFormingColumnName {get;set;}
public decimal MyProperty => MyDictionary[CurrentlyFormingColumnName]
    

and in View

foreach (var name in myKeys)
    {
        ViewModel.MyResultRows.ForEach(x=>x.CurrentlyFormingColumnName = name);
        MyRadGridView.Columns.Add(new GridViewDataColumn()
                                                         {
                                                             Header = name,
                                                             IsReadOnly = true,
                                                            DataMemberBinding = new Binding("MyProperty");
                                                         });
    }

But because MyProperty of an instance of ResultRow is changing each time a new column creates, in every created there will be value of last column of an instance

1

There are 1 answers

4
mm8 On

The following binding should work assuming MyDictionary is a Dictionary<string, decimal> property that contains a name key:

new Binding($"MyDictionary[{name}]")

Note the absence of quotes around the key in the binding path.