Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind an ItemsControl.ItemsSource with 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 associated 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 elements from Activities.

How should I write the binding in XAML?
I tried this but it doesn't work:

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

How do I make this work in XAML?

like image 1000
Jonny Piazzi Avatar asked May 22 '13 14:05

Jonny Piazzi


People also ask

How does binding work in XAML?

Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism.

How do I bind a list in WPF?

<ListView. View> <GridView> <GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=EmployeeID}"/>

What is ItemsSource binding WPF?

ItemsSource can be data bound to any sequence that implements the IEnumerable interface, although the type of collection used does determine the way in which the control is updated when items are added to or removed.


1 Answers

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,

like image 154
sexta13 Avatar answered Nov 15 '22 14:11

sexta13