开发者

WPF ComboBox drop-down (data bound) values not changing

开发者 https://www.devze.com 2022-12-25 23:53 出处:网络
I bind the ItemsSource of a ComboBox开发者_StackOverflow中文版 to an ObservableCollection<MyClass>. In code I change the collection (e.g. edit the MyClass.Name property).

I bind the ItemsSource of a ComboBox开发者_StackOverflow中文版 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


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));
       }
    }  
 }


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消