Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML Binding to a CollectionViewSource property on a ViewModel

Tags:

binding

wpf

xaml

I have a simple ViewModel like:

public class MainViewModel {
    ObservableCollection<Project> _projects;
    public MainViewModel() {
        // Fill _projects from DB here...
        ProjectList.Source = _projects;
        ProjectList.Filter = ...;
    }

    public CollectionViewSource 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 might I be doing wrong?

like image 674
joshperry Avatar asked Jun 09 '10 20:06

joshperry


1 Answers

If you are using CollectionViewSource you need to bind ItemsSource to ProjectList.View instead of ProjectList. That should solve your problem.

like image 62
Joseph Sturtevant Avatar answered Nov 04 '22 09:11

Joseph Sturtevant