【问题标题】:WPF: How do I limit number of items in Combobox ItemsSource?WPF:如何限制 Combobox ItemsSource 中的项目数?
【发布时间】:2012-05-01 07:51:20
【问题描述】:
我创建了一个 WPF 自定义组合框,它能够根据“搜索字符串”过滤项目。 ComboBox ItemsSource 绑定到 ObservableCollection。
ObservableCollection 是“Person”对象的集合。它公开了一个属性“Usage Count”。
现在,如果“搜索字符串”为空,我必须显示 ObservableCollection 中的前 30 条记录。 “Person”类中的“UsageCount”属性决定前 30 条记录(即必须显示具有最大 UsageCount 的前 30 条记录)。
UsageCount 属性动态变化。
我如何实现这一目标..
请帮忙。在此先感谢:)
【问题讨论】:
标签:
wpf
c#-4.0
collectionviewsource
【解决方案1】:
要处理您的可搜索排序集合,您可以构建自己的对象,从 ObverservableCollection 继承,重载 Item 默认属性,添加(通知)SearchString 属性,监听您的 Person 整个列表的更改,基于更改(更改SeachString 或在UsageCount of a Person) 一个新的person 私有列表,并使用NotifyCollectionChanged 事件通知它。
【解决方案2】:
这里有个想法,如果你需要过滤为什么不绑定到 ListCollectionView
in the View
ComboBox ItemsSource="{Binding PersonsView}" //instead of Persons
在您的 ViewModel 中:
public ListCollectionView PersonsView
{
get { return _personsView; }
private set
{
_personsView= value;
_personsView.CommitNew();
RaisePropertyChanged(()=>PersonsView);
}
}
一旦你填充了你的列表
PersonsView= new ListCollectionView(_persons);
在您看来,您显然有一个地方可以响应组合框的更改,您可以在其中更新过滤器,您可以将应用过滤器放在那里
_viewModel.PersonsView.Filter = ApplyFilter;
ApplyFilter 是决定显示内容的操作
//this will evaluate all items in the collection
private bool ApplyFilter(object item)
{
var person = item as Person;
if(person == null)
{
if(person is in that 30 top percent records)
return false; //don't filter them out
}
return true;
}
//or you can do some other logic to test that Condition that decides which Person is displayed, this is obviously a rough sample
}