XAML绑定到CollectionViewSource财产上的视图模型 [英] XAML Binding to a CollectionViewSource property on a ViewModel
问题描述
我有一个简单的视图模型,如:
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; }
}
我设置窗口的DataContext在构造视图模型的一个新实例:
I set the window's DataContext to a new instance of that ViewModel in the constructor:
public MainWindow() {
this.DataContext = new MainViewModel();
}
然后在XAML我试图绑定一个ListBox到ProjectList财产的ItemsSource。
Then in the Xaml I am attempting to bind the ItemsSource of a ListBox to that ProjectList property.
绑定的ItemsSource只是像这样不工作:
Binding just ItemsSource like so doesn't work:
<ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." />
但是,如果我第一次重订这个作品在DataContext:
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?
推荐答案
如果您使用的是 CollectionViewSource
您需要绑定的ItemsSource
到 ProjectList.View
而不是 ProjectList
。这应该解决您的问题。
If you are using CollectionViewSource
you need to bind ItemsSource
to ProjectList.View
instead of ProjectList
. That should solve your problem.
这篇关于XAML绑定到CollectionViewSource财产上的视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!