WPF将已过滤的ObservableCollection ICollectionView绑定到Combobox

我想根据类型(类型AddPoint)将ObservableCollection过滤为子集,并希望它按升序排序,不重复。 我的基类是ModelBase,w /子类AddPoint,Time,Repeat等…… ObservableCollection MotionSequenceCollection将以任何顺序填充这些类型,有些将是重复的。

我已经尝试了几次不同的时间,并在ICollectionView属性中显示它们,我从’拉出’: 绑定集合的子集 。

可观察的收集

private ObservableCollection _motionSequenceCollection = new ObservableCollection(); public ObservableCollection MotionSequenceCollection { get { return _motionSequenceCollection; } set { if (_motionSequenceCollection == value) { return; } var oldValue = _motionSequenceCollection; _motionSequenceCollection = value; // Update bindings, no broadcast RaisePropertyChanged(); } } public ICollectionView Location { get { var location = CollectionViewSource.GetDefaultView(_motionSequenceCollection); //DOES NOT WORK. PROBLEM: GetType() creates type of system.type() and AddPoint, which don't work. Need a cast, or something?? // found at https://stackoverflow.com/questions/9621393/bind-subset-of-collection The problem is that there is an error: // Cannot apply operator '==' to operands of type 'System.Type' and 'MotionSeq.Model.AddPoint', // candidates are: // bool ==(System.Reflection.MemberInfo, System.Reflection.memberInfo) (in class MemberInfo) // bool ==(System.type, System.Type) (in class Type) //location.Filter = p => (p as ModelBase).GetType() == AddPoint; //DOES NOT WORK. PROBLEM: Affects the main collection and won't let TIME type added. //location.Filter = o1 => (o1 is AddPoint); //DOES NOT WORK. PROBLEM: Sorts fine, but also sorts MotionSequenceCollection!! What up w/ that!? //location.SortDescriptions.Add(new SortDescription("AddPointClassName", ListSortDirection.Ascending)); //DOES NOT WORK. PROBLEM: MotionSequenceCollection does not update. //location.Filter = p => (p as ModelBase) == AddPoint; //DOES NOT WORK. PROBLEM: Source is not instantiated(?) and exmaple from stackoverflow and not sure how that got there in the first place. //source.Filter = p => (p as ModelBase).GetType() == "AddPoint"; //return source; return location; } } 

所有集合都有一个默认的CollectionView。 WPF始终绑定到视图而不是集合。 如果直接绑定到集合,WPF实际上会绑定到该集合的默认视图。 此默认视图由​​集合的所有绑定共享,这会导致对集合的所有直接绑定共享一个默认视图的排序,filter,组和当前项特征。

尝试创建CollectionViewSource并设置其过滤逻辑,如下所示:

 //create it as static resource and bind your ItemsControl to it         private void CollectionViewSource_Filter(object sender, FilterEventArgs e) { var t = e.Item as ModelBase; if (t != null) { //use your filtering logic here } } 

按类型过滤很容易。 这应该工作:

 location.Filter = p => p.GetType() == typeof(AddPoint); 

排序也很容易。 您需要做的就是实现IComparer并将其分配给集合视图的CustomSort属性。

没有简单的方法来删除重复(不是我知道)。 我建议你去其他地方做。 例如,您可以区分您的基础集合。