siger
siger

Reputation: 3162

ListBox ItemsSource binding working through code but not through XAML

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.

Upvotes: 4

Views: 3330

Answers (1)

SeeSharp
SeeSharp

Reputation: 1750

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")

Upvotes: 2

Related Questions