ListBox ItemsSource binding works 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 view model page:

 DataContext = App.ViewModel; 

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

 public ObservableCollection<Item> MyItems; 

Ultimately, my ListBox does not display anything. I tried adding elements after snapping, and they also do not appear.

What works if I install ItemSource in code instead of XAML:

 MyItemsList.ItemsSource = App.ViewModel.MyItems; 

Any tips on why this will happen? Thanks.

+4
source share
1 answer

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

Property with support field:

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

If you want to set the setter, you must implement INotifyPropertyChanged and call OnPropertyChanged ("MyItems")

+2
source

Source: https://habr.com/ru/post/1335369/


All Articles