dw.
dw.

Reputation: 13

Silverlight Binding - Binds when item is added but doesn't get updates

I'm sorta at a loss to why this doesn't work considering I got it from working code, just added a new level of code, but here's what I have. Basically, when I bind the ViewModel to a list, the binding picks up when Items are added to a collection. However, if an update occurs to the item that is bound, it doesn't get updated. Basically, I have an ObservableCollection that contains a custom class with a string value. When that string value gets updated I need it to update the List.

Right now, when I debug, the list item does get updated correctly, but the UI doesn't reflect the change. If I set the bound item to a member variable and null it out then reset it to the right collection it will work, but not desired behavior.

Here is a mockup of the code, hopefully someone can tell me where I am wrong. Also, I've tried implementing INofityPropertyChanged at every level in the code below.

public class Class1
{
     public string ItemName;
}

public class Class2
{
     private Class2 _items;

     private Class2() //Singleton
     {
          _items = new ObservableCollection<Class1>();
     }

     public ObservableCollection<Class1> Items
     {
          get { return _items; }
          internal set 
          { 
               _items = value;
          }
     }
}

public class Class3
{

     private Class2 _Class2Instnace;

     private Class3()
     {
          _Class2Instnace = Class2.Instance;
     }

     public ObservableCollection<Class1> Items2
     {
          get {return _Class2Instnace.Items; }
     }
}

public class MyViewModel : INofityPropertyChanged
{
     private Class3 _myClass3;

     private MyViewModel()
     {
          _myClass3 = new Class3();
     }

     private BindingItems
     {
          get { return _myClass3.Items2; }  // Binds when adding items but not when a Class1.ItemName gets updated.
     }
}

Upvotes: 1

Views: 106

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189495

The answer to your question is that Class1 needs to implement INotifyPropertyChanged.

public class Class1 : INotifyPropertyChanged
{
    private string _ItemName;
    public string ItemName
    {
       get { return _ItemName; }
       set
       {
         _ItemName = value;
         NotifyPropertyChanged("ItemName");
       }
    }

    private void NotifyPropertyChanged(string name)
    {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    public event PropertyChangedEventHandler PropertyChanged;

}

Upvotes: 2

Related Questions