Search code examples
c#wpfwpfdatagriddatagridcomboboxcolumn

DataGridComboBoxColumn wont display selected item in cell on ending edit


I'm having an issue when I select an item from a DataGridComboBoxColumn. The cell wont display the name of the item I've chosen after I move focus to the next cell. This is the code I have:

DataGridComboBoxColumn cb1 = new DataGridComboBoxColumn();
cb1.ItemsSource = listOStrings;
cb1.TextBinding = new Binding("listOfStrings");
e.Column = cb1;
e.Column.Header = "SomeTitle";

Where listOfStrings is a list that is being updated by the user. I have another DataGridComboBoxColumn that has its ItemSource set to a list of strings that isn't being updated. That one displays the text just fine, although the code for the two is the same. I'm wondering why my cb1 combo box wont display the values after leaving the cell but the other one does?


Solution

  • When a binding in WPF is hooked up to a non-static source, the underlying source needs to implement iNotifyPropertyChanged. In your case you may want to use an ObservableCollection as answered here: Why does a string INotifyPropertyChanged property update but not a List<string>?

    In your case, it would look something like:

    private ObservableCollection<string> _listOStrings = new ObservableCollection<string>();
    public ObservableCollection<string> ListOStrings 
    {
        get
        {
            return _listOStrings;
        }
    
        set
        {
            _listOStrings = value;
            OnPropertyChanged("ListOStrings");
        }
    }
    

    For more information on iNotifyPropertyChanged from MSDN, see: See: https://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx