Binding ListBox's ItemSource in XAML doesn't work

1k views Asked by At

I have a sample windows phone 7 project where I test some MVVM stuff, however I came across a problem.

My code looks like this:

This is from my View which is a MainPage:

  <Grid>
        <ListBox x:Name="list" ItemsSource="{Binding _reviews}"/>
    </Grid>

This is code behind for the View:

      public MainPage()
        {
            this.Loaded += MainPage_Loaded;
            // Line below makes list show what it is supposed to show
            // list.ItemsSource = (DataContext as MainPageVM)._reviews;
            DataContext = new MainPageVM();
            InitializeComponent();
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // DataContext is set to the right object!
            var obj = list.DataContext;
        }

Code for ViewModel

class MainPageVM
{
    public ObservableCollection<Review> _reviews { get; set; }

    public MainPageVM()
    {
        _reviews = GetReviews();
    }

    private ObservableCollection<Review> GetReviews()
    {
        ObservableCollection<Review> reviews = new ObservableCollection<Review>();
        reviews.Add(new Review() { User = "Lol", Text = "Cool", Country = "UK"});
        reviews.Add(new Review() { User = "misterX", Text = "aWESCOM APP", Country = "USA"});
        reviews.Add(new Review() { User = "meYou", Text = "The best", Country = "UK"});

        return reviews;
    }

And here is my model:

class Review
{
    public string Text { get; set; }
    public string User { get; set; }
    public string Country { get; set; }
}

Could you please point out where is the error and why I am able to set the ItemSource in code behind, but not via binding in XAML

1

There are 1 answers

3
Derek Lakin On BEST ANSWER

The problem is that your view model class does not implement the INotifyPropertyChanged interface and you are not raising the PropertyChanged event, so the view does not know that the property you are binding to has changed.

If you're not sure about how to implement this interface, take a look at this post on Silverlight Show.

UPDATE: For most properties the above is true, however, in this instance because it's an ObservableCollection it's not necessary. However, because your view model class isn't public the view can't bind to it. Do you see any binding errors in the Output window whilst debugging?