views:

59

answers:

2

Hello, I have a Silverlight application in which I implemented MVVM pattern. In my application there is a child window on which I have ComboBox. I bound ItemsSource and SelectedItem of my combobox to a property (typeof ObservableCollection) and property of MyType appropriately. MyType is a "MODEL" derived from INotifyPropertyChanged. When my window is loaded I set values to this properties. But my combobox doesn't display selected item. I found that when I set property which is bound to selected item (in ViewModel), the PropertyChanged event is null. Can anyone help me. Thanks.

A: 

From the way you've described it the only thing being bound to is the ViewModel yet the only thing that implements INotifyPropertyChanged is MyType. Nothing is actually binding to the instance of my type to listen to its PropertyChanged event which is why its null.

It sounds like you haven't implemented INotifyPropertyChanged on your ViewModel.

AnthonyWJones
A: 

PropertyChanged works fine, so it must be in your implementation of it. Simply implementing INotifyProperty changed isn't good enough, you have to explicity call the event.

For example, this will not work:

public class Model : INotifyPropertyChanged
{
    public string Title { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
}

In order for it to work, you must raise the property changed. Easiest way is to encapsulate the logic in a method, like this:

public class Model : INotifyPropertyChanged 
{
   private string _title;

   public string Title
   { 
      get { return _title; }
      set 
      {
         _title = value;
         RaisePropertyChanged("Title");
      }
   }

   protected void RaisePropertyChanged(string propertyName) 
   {
      var handler = PropertyChanged;
      if (handler != null)   
      {
         handler(this, new PropertyChangedEventArgs(propertyName));
      }
   }

    public event PropertyChangedEventHandler PropertyChanged;

}

Of course you can put the event and the method in a base class to inherit from so multiple models can take advantage of it.

Jeremy Likness