XAML Binding to a CollectionViewSource property on a ViewModel
Asked Answered
J

2

12

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?

Jasmin answered 9/6, 2010 at 20:0 Comment(2)
Are you getting your data from the DB synchronously or asynchronously ?Peppermint
synchronously, beside if it was a race condition then the second method would not work either...Jasmin
W
19

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

Workable answered 9/6, 2010 at 20:28 Comment(3)
So I guess I can't duplicate my problem like that either... I've updated the question with what the ViewModel "really" looks like.Jasmin
See my updated answer. I'm not exactly sure why CollectionViewSource works this way, but its the way I've always had to work with them.Workable
Thank you, that's very helpful. This is the first time I've used a CollectionViewSource. I ended up making the property type ICollectionView and in the getter I return the View property from a private CollectionViewSource. That way I don't need to worry about binding to .View which would break if I change the collection type of that ViewModel property in the future.Jasmin
D
0

From what you provided the first method should perfectly work. Devil lurks somewhere in details.

PS: Maybe you didn't specify implementation of INotifyPropertyChanged interface in sake of post size, but be careful in production. It's very easy to get a memory leak if you don't implement it.

Dyna answered 9/6, 2010 at 20:32 Comment(1)
Yes, it actually does implement that interface. Call it a test case if you will.Jasmin

© 2022 - 2024 — McMap. All rights reserved.