我使用ViewModel中定义的ViewModel将(各种类型的)形状呈现给画布。我根据我的底层数据创建了几个ICollectionView。
// ViewModel
ICollectionView view1 = new CollectionViewSource() { Source = ObservableCollectionA }.View;
view1.Filter = ...然后创建一个CompositeCollection以在xaml中绑定:
_CompositeCollection = new CompositeCollection();
var container = new CollectionContainer() { Collection = viewModel.view1 };
_CompositeCollection.Add(container);在视图中,我使用画布的_CompositeCollection将ItemsControl容器绑定到ItemsControl。
画布上没有添加任何东西。如果我将ICollectionView层从ViewModel中移除,并直接在CollectionContainer.Collection中使用ObservableCollection,则工作正常:
var container = new CollectionContainer() { Collection = viewModel.ObservableCollectionA };我不想直接公开ObservableCollection,我认为这与整个MVVM范式是一致的。
CompositeCollection似乎不能正常工作;如何将多个ICollectionViews合并到一个集合中,以便绑定到单个ItemsControl?或者也许有一个更好的结构可以使用?
我正在使用C# 4.0。
发布于 2017-09-21 14:28:38
CollectionViewSource应该是UI的一部分,因为您需要PresentationFramework.dll来使用它。
至于结构,我通常有:
在xaml中:
<CollectionViewSource Source="{Binding CmbList}" x:Key="cmbList"></CollectionViewSource>
<CollectionViewSource Source="{Binding Items}" x:Key="items"></CollectionViewSource><!-- this goes into your Resources tag
<ComboBox>
<ComboBox.ItemsSource><!-- in here we are using multiple types of collections and objects
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource items}}"></CollectionContainer>
<sys:String>Newly added item</sys:String>
<CollectionContainer Collection="{Binding Source={StaticResource cmbList}}"></CollectionContainer>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox> 其中xmlns:sys="clr-namespace:System;assembly=mscorlib"
我的ViewModel将其作为定义的集合:
private string[] _items;
public string[] Items
{
get { return _items; }
set { _items = value; OnPropertyChanged("Items"); }
}
private List<int> _cmbList;
public List<int> CmbList
{
get { return _cmbList; }
set { _cmbList = value; OnPropertyChanged("CmbList"); }
}正如您将看到的,这将显示2种非常不同类型的集合,以及我们创建的附加项。
https://stackoverflow.com/questions/46345719
复制相似问题