通过关注this博文,我试图在WPF应用程序中添加搜索和过滤功能。它是一个文件浏览器应用程序,我正在读取驱动器中的所有文件,文件夹,并使用MVVM我将其内容与UI(Listbox
)绑定。但是,当我使用CollectionViewSource
添加另一个图层来过滤数据时,我无法在UI上看到过滤后的数据。
如果有人能解释我如何在UI中看到过滤后的数据,我们将不胜感激。谢谢。
代码
public DefaultControl()
{
Instance = this;
InitializeComponent();
this.DataContext = this;
}
// When the listbox is initialized
private void detailList_Initialized(object sender, EventArgs e)
{
var data = DirectoryStructure.
GetDirectoryContent(DirectoryPath).
Select(drive => new DirectoryItem(drive.FullPath, drive.Type)).ToList();
Items = new ObservableCollection<DirectoryItemViewModel>(data);
CollectionViewSource.GetDefaultView(Items).Filter = Search;
}
private bool Search(object obj)
{
if (String.IsNullOrEmpty(txtBx_Search.Text))
return true;
var item = (DirectoryItemViewModel)obj;
bool found = (item.Name.Contains(txtBx_Search.Text));
return found;
}
// Listen the text change event of Textbox
private void OnSearchTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
CollectionViewSource.GetDefaultView(Items).Refresh();
}