0

I want to display a dictionary<string, string> and edit it in a wpf application.

I've tried to Bind the dictionary to a DataGrid but was not successful. I also tried to transform the dictionary into a Database, pass it to the DataGrid as its ItemsSource but after I edit it, I cannot retrieve it back.

Thanks!

  • Please provide enough code so others can better understand or reproduce the problem. – Community Jul 22 '22 at 12:47
  • @ASh - your statement may be confusing because: https://dotnetfiddle.net/z9Y6GB seems mutable – Rand Random Jul 22 '22 at 12:50
  • @RandRandom, Dictionary is mutable, obviously. you don't have any operations with KeyValuePair. e.g. `KeyValuePair kvp = dict.First(); kvp.Value = "change";` produces compile time error: `Property or indexer 'KeyValuePair.Value' cannot be assigned to -- it is read only`. that makes direct editing via DataGrid impossible – ASh Jul 22 '22 at 12:53
  • Does this answer your question? [IDynamicMetaObjectProvider.GetMetaObject is not always called](https://stackoverflow.com/questions/20745780/idynamicmetaobjectprovider-getmetaobject-is-not-always-called) – T. Nielsen Jul 22 '22 at 13:25

1 Answers1

0

You would not bind or edit a dictionary directly. You should instead create a list of key and value pairs to bind to, something like:

public class MyKeyValue : INotifyPropertyChanged{
    public string Key {get;set;}
    public string Value {get;set;}
    // Implement INotifyPropertyChanged with proper setters etc.
}
public ObservableCollection<MyKeyValue> MyList = new ();
public Dictionary<string,string> GetDictionary() => MyList.ToDictionary(i => i.Key, i => i.Value);

Bind this to a datagrid, or a listView or whatever control you prefer.

I would probably recommend making the Key readonly, and have a dedicated field for adding key/values. That way you have a place to check for duplicated keys and show an appropriate warning.

JonasH
  • 28,608
  • 2
  • 10
  • 23