XAML Binding to a CollectionViewSource property on a ViewModel

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-19 05:17:26

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3009454/xaml-binding-to-a-collectionviewsource-property-on-a-viewmodel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!