我正在為一個集合制作一個過濾器。
我知道如何使用 CollectionViewSource 來做到這一點。
但我想在不使用 CVS 的情況下做到這一點。
根據我的想法,ItemsControl.Items屬性中有一個CollectionView,可以使用該屬性的方法。
可以毫無問題地添加過濾器。
但是在呼叫 Items.Refresh() 之后沒有任何變化。
簡單的例子:
<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();
}
}
我誤解了什么或做錯了什么?
更新。 基于@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);
}
uj5u.com熱心網友回復:
是ItemsControl.Items型別ItemsCollection。ItemsCollection實作不同的Refresh行為。該Items物業基本上是供內部使用的。如果你必須依賴CollectionView.Refresh你應該CollectionView明確使用:
ItemsControl itemsControl;
itemsControl.Items.Filter = item => (item as string).Contains("A");
CollectionView collectionView = CollectionViewSource.GetDefaultView(itemsControl.ItemsSource);
collectionView.Refresh();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416881.html
標籤:
上一篇:在檔案夾內迭代并僅復制子檔案夾
