目前,我有绑定到项目集合的列表框。由于收集大,我们要筛选的项目是基于输入的一个文本框中的文本显示。
I currently have a ListBox binded to a collection of items. As the collection is big we want to filter the items being shown based on the text entered on a TextBox.
如果这是可以实现只用XAML,我不想修改项目的集合就是我要问的是,我想修改每个基于过滤器项目的可见性。
What I'm asking is if this is possible to implement using only XAML, I don't want to modify the collection of items, I would like to modify the Visibility of each of the items based on the filter.
希望其明确的,
谢谢!
像codeNaked和devdigital告诉你CollectionViewSource /的CollectionView / ICollectionView的 的关键是你的目标
Like CodeNaked and devdigital told you CollectionViewSource/CollectionView/ICollectionView are the keys to your goal
这是一个MVVM图案,但是这是一个只查看相关的问题,所以我不知道 希望这个code。在视图模型。
It's a MVVM patter but this is a View only related problem so I don't want this code at the ViewModel.
这就是不正确的做法,因为该视图只显示了她get's但shouldn't modifi 所以应该/必须是你的ViewModel谁韩德尔的变化
thats not the right way because the View only shows what she get´s but shouldn´t modifi so it should/must be your ViewModel who handel changes
所以现在一些code剪:
so now some code snips:
public class myVM
{
public CollectionViewSource CollViewSource { get; set; }
public string SearchFilter
{
get;
set
{
if(!string.IsNullOrEmpty(SearchFilter))
AddFilter();
CollViewSource.View.Refresh(); // important to refresh your View
}
}
public myVM(YourCollection)
{
CollViewSource = new CollectionViewSource();//onload of your VM class
CollViewSource.Source = YourCollection;//after ini YourCollection
}
}
XAML中剪断:
Xaml Snip:
<StackPanel>
<TextBox Height="23" HorizontalAlignment="Left" Name="tB" VerticalAlignment="Top"
Width="120" Text="{Binding SearchFilter,UpdateSourceTrigger=PropertyChanged}" />
<DataGrid Name="testgrid" ItemsSource="{Binding CollViewSource.View}"/>
</StackPanel>
编辑我忘了过滤器
Edit i forgot the Filter
private void AddFilter()
{
CollViewSource.Filter -= new FilterEventHandler(Filter);
CollViewSource.Filter += new FilterEventHandler(Filter);
}
private void Filter(object sender, FilterEventArgs e)
{
// see Notes on Filter Methods:
var src = e.Item as YourCollectionItemTyp;
if (src == null)
e.Accepted = false;
else if ( src.FirstName !=null && !src.FirstName.Contains(SearchFilter))// here is FirstName a Property in my YourCollectionItem
e.Accepted = false;
}