ListBox CollectionViewSource.Filter方法问题
我在 XAML 中定义了一个列表框,并使用从文本框获取的文本中的以下代码来过滤其项目:
if (list.Items.Count > 0)
{
CollectionViewSource.GetDefaultView(list.Items).Filter =
new Predicate<object>((item) => {
string valtoCheck = item.ToString();
return valtoCheck.StartsWith(filterText,
StringComparison.CurrentCultureIgnoreCase);
});
}
一切正常,除了过滤器找不到与条件匹配的项目的情况。
前任。假设我的列表中有 4 个项目:Rob
、Bob
、Andy
、John
。
当我输入 Ro
时,列表会相应地进行过滤(显示 rob)。
当我输入 b
时,列表会被适当过滤(显示 bob)。
但是,如果我输入 z
(目标列表变为空),我会得到一个空列表,这是正确的;但从那时起,List.Items.Count 被设置为零。该列表变为空。我假设输入替换的 b
应该显示 Bob
但事实并非如此;一旦我输入列表框中任何项目中不包含的文本,列表的项目就会设置为空!
我在这里错过了什么吗?
I have a listbox defined in XAML and I filter its items using the following code from text obtained from a textbox:
if (list.Items.Count > 0)
{
CollectionViewSource.GetDefaultView(list.Items).Filter =
new Predicate<object>((item) => {
string valtoCheck = item.ToString();
return valtoCheck.StartsWith(filterText,
StringComparison.CurrentCultureIgnoreCase);
});
}
Everything works fine, except in the case where the filter finds no items matching the criteria.
ex. Lets say I have 4 items in the list : Rob
,Bob
,Andy
,John
.
When I enter Ro
, the list filters accordingly (shows rob).
When I enter b
, the list gets filtered appropriately (shows bob).
However, if i enter z
(the target list becomes empty), I get an empty list which is correct; but then List.Items.Count is set to zero from that point on. The list becomes empty. I would assume that typing a replacement b
should show me Bob
but it does not; the list's items are set to empty as soon as I enter text that is not contained in any of the items in the listbox!
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为你不能消除 if 条件检查,只是有
I dont see you cannot eliminate the if condition check and just have
如果不查看更多周围的代码,很难判断,但此类问题通常与未在正确的时间调用 Refresh 有关。看起来您可能会一遍又一遍地重新分配过滤器,而不是设置一次并在过滤器文本更改时刷新。
It's hard to tell without seeing more of the surrounding code but issues like this are usually related to Refresh not being called at the right times. It also looks like you may be reassigning the Filter over and over instead of setting it once and refreshing when the filter text changes.