Jonny Piazzi Jonny Piazzi - 2 months ago 13
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"
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>


O .cs is like this

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

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

// Other code ...
}


If I write in constructor something like this:

lvItems.ItemsSource = Activities;


When I add or remove elements from
Activities
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

What @JesseJames says is true but not enough.

You have to put

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

as

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

And the binding should be:

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

Regards,

Comments