Search code examples
c#wpfcomboboxbindingselectedvalue

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


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?


Solution

  • Took a while to figure out, I was setting things correctly, but because I was updating the same property in the setter, I needed to use a dispatcher to create a new thread to do the update correctly.