Jonny Piazzi Jonny Piazzi - 10 months ago 41
C# Question

How to Bind an ItemsControl.ItemsSource with a property of the window in WPF?

Hi I have a Window like this:

<Window x:Class="WinActivityManager"
<ListView x:Name="lvItems" />

O .cs is like this

public partial class WinActivityManager : Window
private ObservableCollection<Activity> Activities { get; set; }

public WinActivityManager()
Activities = new ObservableCollection<Activity>();

// Other code ...

If I write in constructor something like this:

lvItems.ItemsSource = Activities;

When I add or remove elements from
my ListView is automatically update.

Ok. But How I wrote this binding line in XAML?

I try this but don't work:

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

How I can do this work in XAML?

Answer Source

What @JesseJames says is true but not enough.

You have to put

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


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

And the binding should be:

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