收集ViewSource以通过键入文本框来过滤列表框 [英] Collection ViewSource to filter listbox by typing in textbox
本文介绍了收集ViewSource以通过键入文本框来过滤列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在WPF中有一个列表框,其中列出了用户的名字和姓氏。我有一个文本框,我试图按名称进行过滤。这是我正在尝试的:(当我在文本框中输入时没有任何东西被过滤)
这是我的VM
I have a listbox in WPF where users firstname and lastname are listed. I have a textbox, and I am trying to filter as I type by the names. Here is what I am trying: (Nothing is being filtered when I am typing in the textbox)
Here is my VM
#region Members
private ObservableCollection<User> mUser = new ObservableCollection<User>();
private CollectionViewSource usercvs = new CollectionViewSource();
private string searchString;
#endregion
#region Properties
public ObservableCollection<User> Users
{
get
{
return mUser;
}
}
public string SearchFilter
{
get
{
return this.searchString;
}
set
{
if (!string.IsNullOrEmpty(this.searchString))
AddFilter();
usercvs.View.Refresh();
this.searchString = value;
}
}
#endregion
#region Methods
private void AddFilter()
{
usercvs.Filter -= new FilterEventHandler(Filter);
usercvs.Filter += new FilterEventHandler(Filter);
}
private void Filter(object sender, FilterEventArgs e)
{
// see Notes on Filter Methods:
var src = e.Item as User;
if (src == null)
e.Accepted = false;
else if (src.LastName != null && !src.LastName.Contains(SearchFilter))
e.Accepted = false;
}
#endregion
}
}
推荐答案
修改您的过滤器事件处理程序...
如果部件应该包含其他内容
Modify your Filter event handler ...
the else if part should contain
e.accepted = src.LastName.Contains(SearchFilter);
set e.Accepted = false;对于您想要过滤的所有条件和
设置e.Accepted = true;对于其他人
set e.Accepted = false; for all conditions which you want to filter and
set e.Accepted = true; for others
通过添加IcollectionView属性并将列表框绑定到该属性来获得它。
Got it by adding a IcollectionView property and binding the listbox to that property.
public ICollectionView FilteredUsers
{
get
{
return usercvs.View;
}
}
这篇关于收集ViewSource以通过键入文本框来过滤列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文