views:

139

answers:

2

I bind the ItemsSource of a ComboBox to an ObservableCollection<MyClass>. In code I change the collection (e.g. edit the MyClass.Name property).

The problem: the change is not reflected in the dropdown box if the ComboBox, yet when I seled the item from the dropdown it is displayed correctly in the selected item box of the ComboBox.

What's going on? :)

PS MyClass has INotifyPropertyChanged implemented

+1  A: 

I suspect that INotify... is not correctly implemented? I just tested:

     l = new ObservableCollection<MyClass>();
     l.Add(new MyClass() { Name = "A" });
     l.Add(new MyClass() { Name = "B" });
     l.Add(new MyClass() { Name = "C" });
     cmb.ItemsSource = l;

and then, on a button click:

     l[0].Name = "Robert";

works just fine. My combobox:

    <ComboBox x:Name="cmb" SelectedValuePath="Name" DisplayMemberPath="Name" />

and finally, my class:

 class MyClass : INotifyPropertyChanged
 {
    private string _name;
    public string Name
    {
       get
       {
          return _name;

       }
       set
       {
          string oldval = _name;
          _name = value;
          if (!string.Equals(oldval, _name))
          {
             OnPropertyChanged("Name");
          }
       }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string name)
    {
       var ev = PropertyChanged;
       if (ev != null)
       {
          ev.Invoke(this, new PropertyChangedEventArgs(name));
       }
    }  
 }
Robert Jeppesen
Thanks for the answer, but (as always) the problem was in my dummy head.Again, thanks for the suggestion!
Jefim
A: 

I am sorry that this was even a question here. The problem was that I just forgot to set the Binding Path in the DataTemplate and it was using the ToString method to display elements. This messed up the binding.

So remember - if you override the ToString always check that you do not use it in a binding :)

Jefim