4

I have this XAML:

<ListBox x:Name="MyItemsList"                         
     ItemsSource="{Binding MyItems}" 
     SelectionChanged="ItemsList_SelectionChanged">

The code behind assigns the datacontext of the page to the view model:

DataContext = App.ViewModel;

My ViewModel object defines MyItems (and I initialize MyItems before setting the DataContext):

public ObservableCollection<Item> MyItems;

The end result is that my ListBox doesn't display anything. I tried adding items after the binding, and they don't show up either.

What works is if I set the ItemsSource in code instead of in the XAML:

MyItemsList.ItemsSource = App.ViewModel.MyItems;

Any tips on why this would happen? Thanks.

siger
  • 3,112
  • 1
  • 27
  • 42

1 Answers1

2

public ObservableCollection MyItems; - Field, but you should use property!

Property with backing field:

private ObservableCollection<Item> _myItems = new ObservableCollection<Item>();
public ObservableCollection<Item> MyItems{get{return _myItems;}}

If you whant setter, you should implement INotifyPropertyChanged and call OnPropertyChanged("MyItems")

SeeSharp
  • 1,730
  • 11
  • 31
  • Good point; but it didn't resolve my issue. If I put a random name as the ItemsSource property in XAML, it also doesn't give me an error (not at build, not at runtime), is that expected? Right now MyItems is a property with { get; set; } and the ListBox is still empty. – siger Jan 13 '11 at 08:15
  • I changed my collection to have a getter return the private collection. It still doesn't work, I guess somewhere else in my code there's a problem. I'll just set the binding through code then because it's taking too much time to figure this out. Thanks for your help. – siger Jan 14 '11 at 06:34
  • There were no binding errors in the VS output window, but I solved my problem by looking at the sample VS project for a databound WP project. I did a few modifications including setting DataContext in the MainPage.xaml.cs constructor. Thanks! – siger Jan 16 '11 at 02:26