Reputation: 7943
I am making a filter for a collection.
I know how to do it using CollectionViewSource.
But I wanted to do it without using CVS.
According to my ideas, there is a CollectionView in the ItemsControl.Items property and you can use the methods of this property.
The filter can be added without problems.
But after calling Items.Refresh() nothing changes.
Simple example:
<UniformGrid Columns="2">
<FrameworkElement.Resources>
<sc:StringCollection
x:Key="coll">
<sys:String>112</sys:String>
<sys:String>22</sys:String>
<sys:String>33</sys:String>
<sys:String>114</sys:String>
<sys:String>411</sys:String>
</sc:StringCollection>
<CollectionViewSource
x:Key="cvs"
Source="{Binding Mode=OneWay, Source={StaticResource coll}}"
Filter="OnFilterCV"/>
</FrameworkElement.Resources>
<TextBox x:Name="tBox"
Text="1"
TextChanged="OnTextChanged"
VerticalAlignment="Center"/>
<TextBox x:Name="tBoxCV"
Text="1"
TextChanged="OnTextChangedCV"
VerticalAlignment="Center"/>
<ItemsControl x:Name="iCtrl"
ItemsSource="{Binding Mode=OneWay, Source={StaticResource coll}}">
</ItemsControl>
<ItemsControl x:Name="iCtrlCV"
ItemsSource="{Binding Mode=OneWay, Source={StaticResource cvs}}">
</ItemsControl>
</UniformGrid>
public partial class MainWindow : Window
{
private readonly CollectionViewSource cvs;
public MainWindow()
{
InitializeComponent();
iCtrl.Items.Filter = OnFilter;
cvs = (CollectionViewSource)iCtrlCV.FindResource("cvs");
}
private bool OnFilter(object obj)
{
if (string.IsNullOrWhiteSpace(tBox.Text))
return true;
string item = (string)obj;
return item.Contains(tBox.Text, StringComparison.OrdinalIgnoreCase);
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
Debug.WriteLine($"OnTextChanged:\"{tBox.Text}\"");
iCtrl?.Items.Refresh();
}
private void OnFilterCV(object sender, FilterEventArgs e)
{
e.Accepted = string.IsNullOrWhiteSpace(tBoxCV.Text) ||
((string)e.Item).Contains(tBoxCV.Text, StringComparison.OrdinalIgnoreCase);
}
private void OnTextChangedCV(object sender, TextChangedEventArgs e)
{
Debug.WriteLine($"OnTextChangedCV:\"{tBoxCV.Text}\"");
cvs?.View.Refresh();
}
}
Am I misunderstanding something or doing something wrong?
Updated. Solution based on comment from @BionicCode.
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
Debug.WriteLine($"OnTextChanged:\"{tBox.Text}\"");
//iCtrl?.Items.Refresh();
if (iCtrl != null)
iCtrl.Items.Filter = new Predicate<object>(OnFilter);
}
Upvotes: 1
Views: 631
Reputation: 29018
The ItemsControl.Items
is of type ItemsCollection
. ItemsCollection
implements a different Refresh
behavior. The Items
property is basically intended for internal use. If you have to rely on CollectionView.Refresh
you should use the CollectionView
explicitly:
ItemsControl itemsControl;
itemsControl.Items.Filter = item => (item as string).Contains("A");
CollectionView collectionView = CollectionViewSource.GetDefaultView(itemsControl.ItemsSource);
collectionView.Refresh();
Upvotes: 2