WPF - Filtering/Searching multiple collection views within a treeview
I have a treeview that is bound to a collection and each item in the collection is bou开发者_运维技巧nd to another collection. (using hierachle data templates)
I would like to use the collection view .Filter event handler to search the tree. The problem is that I need multiple collection views.
What would be the best way to filter the tree view items for example by a search word? I can do this with a single binding of a collection, but once there are collections within collections I have trouble.
The easiest way I found to do this is create a SearchFilter Property
public string SearchFilter
{
get { return _searchFilter; }
set
{
_searchFilter = value;
OnPropertyChanged("MyTreeViewBoundCollection");
}
}
You bind the search filter to a text box, and everytime the search text box changes you notify that the collection has changed
<TextBox Text="{Binding Path=TemplateDataSchema.SearchFilter, UpdateSourceTrigger=PropertyChanged}"/>
Once the change has occured on the SearchFilter, The WPF binding system will requery the Collection Property, which can then be filtered down
public ObservableCollection<Category> MyTreeViewBoundCollection
{
get {
if (_searchFilter.Trim().Length < 1)
return myObject.Categories;
else
{
ObservableCollection<Category> cats = new ObservableCollection<Category>();
string searchText = _searchFilter.ToLower().Trim();
foreach (Category cat in myObject.Categories)
{
Category tmpCat = new Category(cat.CategoryName);
foreach (Field field in cat.Fields)
{
if (field.DataDisplayName.ToLower().Contains(searchText))
tmpCat.Fields.Add(field);
}
if (tmpCat.Fields.Count > 0)
cats.Add(tmpCat);
}
return cats;
}
}
}
This will only return the filter collection.
精彩评论