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!
CodePudding user response:
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.
CodePudding user response:
What you need to do is to read this page in a relaxed environment https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/binding-sources-overview?view=netdesktop-6.0
or youtube databinding in wpf and binding source types
Essentially you need to provide a datasource that your xaml stuff can interact with, and you have some choices. Traditionally we would use an DataTable with two columns, but go ahead choose what dataprovider you want to build otherwise you totally can, like in this example
IDynamicMetaObjectProvider.GetMetaObject is not always called
See the accepted answer is doing what you want to do, have marked question as duplicate even if it is in fact the answer that is