Binding Combobox with Dictionary object, but setting selected value in code behind not taking effect

Tim picture Tim · Nov 18, 2011 · Viewed 8.1k times · Source

Here is my ComboBox instantiated in the XAML

<Combobox ItemsSource="{Binding Path=Delimiters}" DisplayMemberPath="Key"
          SelectedValue="{Binding Path=SelectedDelimiter, UpdateSourceTrigger=PropertyChanged}" />

Here is the corresponding bindings in the view model with the Dictionary populated in the constructor:

private IDictionary<string,string> _delimiters;

public IDictionary<string,string> Delimiters
{
   get{return _delimiters;}
   set{_delimiters = value;  RaisePropertyChanged("Delimiters");}
}

private KeyValuePair <string, string> _selectedDelimiter;
public KeyValuePair <string, string> SelectedDelimiter
{
    get{return _selectedDelimiter;}
    set{
       if(value.Key != _selectedDelimiter.Key || value.Value != _selectedDelimiter.Value)
       {
           var prevDelimiter = _selectedDelimiter;
           _selectedDelimiter = value;
           if(IllegalDelimiter.Contains(_selectedDelimiter)
           {
                 MessageBox.Show("errror", "error");
                 _selectedDelmiter = prevDelimiter;
           }
           RaisePropertyChanged("SelectedDelimiter");
       }

    }
}

I am having trouble with binding the selected value back. The Dictionary is getting bound and when I make a changed to the UI ComboBox, the setting is being fired correctly. In the if statement to check if its an illegal delimiter, it does set the selected value back to its original value in the code behind, but it doesn't populate to the ComboBox UI (I see the get accessor firing from the UI). Its like setting SelectedValue doesn't really do anything to the UI.

if someone could point me in the right direction?

Answer

H.B. picture H.B. · Nov 19, 2011

You should set SelectedValuePath if you are going to use the SelectedValue, presumably to Value. SelectedValue is doing a "selection", so your property type should be different as well.

If you want to retain the whole KeyValuePair you should bind the SelectedItem instead.