0

I have a simple WPF form with a ComboBox and a button. The ComboBox's ItemSource is a Dictionary which includes names of files in a directory. The button is for adding new files by copying them using Open File Dialog.

Code i used for binding:

cmbClasses.ItemsSource = classList;
cmbClasses.DisplayMemberPath = "Key";
cmbClasses.SelectedValuePath = "Value";

I want the ComboBox to refresh items after adding new file to Dictionary and set is as SelectedItem. I tried this for refreshing but it didn't work:

cmbClasses.Items.Clear();
cmbClasses.ItemsSource = classList;
cmbClasses.DisplayMemberPath = "Key";
cmbClasses.SelectedValuePath = "Value";

I saw a few questions here but none of them helped. Anyone know how can i do that?

cameloper
  • 297
  • 1
  • 3
  • 16

1 Answers1

1

First, databind the ItemsSource to an observable collection Property or something else that can and will notify property changed events. This should update the combobox list when the list changes behind the scenes. Databind the selected value to another Property and dynamically set that value to be the value you just added. Here's one way of doing it... a quick Google search will turn up a ton of other tutorials/examples. Good luck and hope this helped!

Community
  • 1
  • 1
Panh
  • 225
  • 1
  • 9
  • After i saw your comment i made a digging about Observable Dictionary and found a [user-made class](http://drwpf.com/blog/2007/09/16/can-i-bind-my-itemscontrol-to-a-dictionary/). You may want to take a look! – cameloper Mar 08 '16 at 19:06
  • 1
    Yes - that would work. The ObservableDictionary notifies when it changes - exactly what you're after. There is also ObservableList and others. You can also make your own. I noticed in the link I gave you, it explicitly sends the name of the property it is notifying changed. In newer versions of .Net, you can use the MemberCallerName attribute instead which makes the code "cleaner" in my opinion. – Panh Mar 09 '16 at 14:56