How to bind an ItemsControl.ItemsSource object to a property in XAML?

I have a simple window:

<Window x:Class="WinActivityManager" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <ListView x:Name="lvItems" /> </Grid> </Window> 

And the related code behind:

 public partial class WinActivityManager : Window { private ObservableCollection<Activity> Activities { get; set; } public WinActivityManager() { Activities = new ObservableCollection<Activity>(); InitializeComponent(); } // Other code ... } 

If I write the following binding in the window constructor:

 lvItems.ItemsSource = Activities; 

then my ListView is automatically updated when I add or remove items from Activities .

How to write binding in XAML?
I tried this, but it does not work:

 <ListView x:Name="lvItems" ItemsSource="{Binding=Activities}" /> 

How to do this in XAML?

+7
source share
4 answers

What @JesseJames says is true, but not enough.

You have to put

 private ObservableCollection<Activity> Activities { get; set; } 

but

 public ObservableCollection<Activity> Activities { get; set; } 

And the binding should be:

 <ListView x:Name="lvItems" ItemsSource="{Binding Path=Activities}" /> 

Hi,

+12
source

You must set the DataContext for this , like the others, but you can also set the DataContext via xaml :

 <Window x:Class="WinActivityManager" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <ListView x:Name="lvItems" ItemsSource="{Binding=Activities}" /> </Grid> </Window> 
+11
source

Set DataContext = this in the window constructor.

 public WinActivityManager() { Activities = new ObservableCollection<Activity>(); DataContext = this; InitializeComponent(); } 

Then you can bind the actions as you like: <ListView x:Name="lvItems" ItemsSource="{Binding=Activities}" />

+2
source

This is because the data context of your view is not set. You can either do it in the code behind:

 this.DataContext = this; 

Alternatively, you can set the Window DataContext for yourself - DataContext="{Binding RelativeSource={RelativeSource Self}}"

You are much better off exploring the MVVM design pattern and using the MVVM framework .

+1
source

All Articles