shtkuh
shtkuh

Reputation: 459

Data Binding and INotifyPropertyChanged

I have ComboBox that takes data from another class

public partial class MainWindow : Window
{
      private ObservableCollection<MyDataClass> _myList = new ObservableCollection<MyDataClass>();

      public MainWindow()
      {
           InitializeComponent();
           comboBox1.DataContext = _myList;
      }

      private void Button_Click(object sender, EventArgs e)
      {
           _myList = AnotherClass.SomeMethod();
      }
}

The only way to update ComboBox data after button click is to implement INotifyPropertyChanged interface in MyDataClass or there are another ways to do that? I look for another way because MyDataClass is generated from web-service so I need to create some adapter class to implement INotifyPropertyChanged

Upvotes: 1

Views: 1802

Answers (2)

Louis Kottmann
Louis Kottmann

Reputation: 16648

public partial class MainWindow : Window, INotifyPropertyChanged
{
      private ObservableCollection<MyDataClass> m_myList;
      public ObservableCollection<MyDataClass> _myList
      {
         get
         {
             return m_myList;
         }
         set
         {
             m_myList = value;
             RaisePropertyChanged("_myList");
         }
      }

      public MainWindow()
      {
           InitializeComponent();
           _myList = new ObservableCollection<MyDataClass>();
           comboBox1.DataContext = _myList;
      }

      private void Button_Click(object sender, EventArgs e)
      {
           _myList = AnotherClass.SomeMethod();
      }

      public event PropertyChangedEventHandler PropertyChanged;
      public void RaisePropertyChanged(String _Prop)
      {
          if (PropertyChanged != null)
          {
              this.PropertyChanged(this, new PropertyChangedEventArgs(_Prop));
          }
      }
}

This is because you're actually assigning a value to a property, you're not updating the ObservableCollection.
Thus it needs to be treated as a property, and you have to implement INotifyPropertyChanged.

And by the way, WCF DataContracts automatically implement INotifyPropertyChanged.

Upvotes: 1

Bek Raupov
Bek Raupov

Reputation: 3777

well, you are using ObservableCollection, so if you dont want to implment INPC, then you can clear out the collection and readd it back with new data. Make sure you are adding/removing from ObservableCollection on the GUI thread. You might want to see how Dispatcher works

Upvotes: 0

Related Questions