Binding Listbox ItemsSource to property of ViewModel in DataContext in WPF

Posted by joshperry on Stack Overflow See other posts from Stack Overflow or by joshperry
Published on 2010-06-09T20:00:32Z Indexed on 2010/06/09 20:02 UTC
Read the original article Hit count: 1038

Filed under:
|

I have a simple ViewModel like:

public class MainViewModel {
    public MainViewModel() {
        // Fill collection from DB here...
    }

    public ObservableCollection<Projects> ProjectList { get; set; }
}

I set the window's DataContext to a new instance of that ViewModel in the constructor:

public MainWindow() {
    this.DataContext = new MainViewModel();
}

Then in the Xaml I am attempting to bind the ItemsSource of a ListBox to that ProjectList property.

Binding just ItemsSource like so doesn't work:

<ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." />

But if I first rebase the DataContext this works:

<ListBox DataContext="{Binding ProjectList}" ItemsSource="{Binding}" ItemTemplate="..." />

Shouldn't the first method work properly? What am I doing wrong?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about wpf-binding