XAML绑定到ViewModel上的CollectionViewSource属性

jos*_*rry 12 wpf xaml binding

我有一个简单的ViewModel,如:

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

    public CollectionViewSource ProjectList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我将窗口的DataContext设置为构造函数中该ViewModel的新实例:

public MainWindow() {
    this.DataContext = new MainViewModel();
}
Run Code Online (Sandbox Code Playgroud)

然后在Xaml中,我试图将ListBox的ItemsSource绑定到该ProjectList属性.

像这样绑定ItemsSource是行不通的:

<ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." />
Run Code Online (Sandbox Code Playgroud)

但是,如果我首先重新定义DataContext,它的工作原理如下:

<ListBox DataContext="{Binding ProjectList}" ItemsSource="{Binding}" ItemTemplate="..." />
Run Code Online (Sandbox Code Playgroud)

第一种方法不应该正常工作吗?我可能做错了什么?

Jos*_*ant 18

如果您使用的是CollectionViewSource需要绑定ItemsSourceProjectList.View代替ProjectList.那应该可以解决你的问题.

  • 谢谢,这非常有帮助.这是我第一次使用CollectionViewSource.我最终创建了属性类型`ICollectionView`,在getter中我从私有CollectionViewSource返回`View`属性.这样我就不用担心绑定到`.View`,如果我将来更改该ViewModel属性的集合类型,它会破坏. (4认同)