Update: Just need to return a key from a dictionary, the dictionary is created by a web service, and passed back to my program which is a WPF, the dictionary is then populated into a dropdown that contains the following values
IT_ED
IT_FS
IT_BUS
The keys are assigned are as follows
Key Value
[1] IT_ED
[2] IT_FS
[3] IT_BUS
I need the key from the value, based on which item is selected in the drop down menu
Dictionary i use to house the keys
private Dictionary<int, string> _DivisionDict = new Dictionary<int, string>();
private Dictionary<int, string> DivisionDict
{
get { return _DivisionDict; }
set { _DivisionDict = value; }
}
Heres how I populate my drop down menu and the dictionary with the keys
foreach (var D in Divisions)
{
txtY.Items.Add(D.Value);
DivisionDict.Add(D.Key, D.Value);
}
Ok, that’s better now (the question),
So, if I get it right you’d like to get back an ‘index’ from the selected item in the WPF dropdown (i.e. ComboBox).
First, easiest is to do a proper data ‘binding’ through your view-model,
you did create,
YourDictionarySelectedItemandYourDictionaryProperty) are properties in your view model. One exposes Dictionary ‘as is’, and another is KeyValuePair …SelectedItem. Just FYI,…then in your
YourDicitonarySelecteItemin your view model – you’ll have the KeyValuePair from the dictionary. And from that you know both index and the value.Or a
brute forcewould be to find the selected value (if you have that as ‘output’ based on how you currently set things up) in the dictionary via e.g. LINQ like this……that’d give you the ‘pair’ and from that take the
Key.hope we nailed it this time:), cheers
EDIT: proper dictionary binding was not in the original scope so it’s a fast fix solution. If you need to update the dictionary ‘from behind’ you’d need to use some observable collection – or force OnPropertyChanged on the full dictionary whenever its items change. See this link for more specific info on that,
Two Way Data Binding With a Dictionary in WPF