我正在尝试将过滤器添加到我的 ListView。过滤器依赖于来自 TextBox 的输入。我正在向 ListView 添加一个过滤器,并在 TextBox 输入发生更改时触发刷新。我的问题:过滤方法只被调用一次。
我有的:
我在 XAML 文件中有一个 ListView。
<TextBox Grid.Row="0" x:Name="textBoxGroupLayers" FontSize="14" TextChanged="textBoxGroupLayers_TextChanged"/>
<ListView Grid.Row="1" x:Name="listViewGroupLayers" FontSize="14" />
我通过添加项目到 ListView
listViewGroupLayers.Items.Add(itemToAdd);
我正在添加过滤器:
this.listViewGroupLayers.Items.Filter = UserFilter;
注意:listViewGroupLayers 是 ListView,listViewGroupLayers.Items 是 ItemCollection。
我的过滤器:
private bool UserFilter(object item)
{
if (String.IsNullOrEmpty(this.textBoxGroupLayers.Text))
{
return true;
}
else
{
MyObject myObject = (item as ListViewItem).Tag as MyObject;
if (myObject == null)
{
return true;
}
bool itemShouldBeVisible = myObject.Name.IndexOf(this.textBoxGroupLayers.Text, StringComparison.OrdinalIgnoreCase) >= 0;
return itemShouldBeVisible;
}
}
刷新:
private void textBoxGroupLayers_TextChanged(object sender, TextChangedEventArgs e)
{
this.listViewGroupLayers.Items.Refresh();
}
现在发生以下情况:我在 UserFilter 中设置了断点。如果我在 TextBox 中键入第一个字母,则断点将处于活动状态并且过滤器工作正常。但是,如果我现在键入第二个字母,则不会调用过滤器。
如果我只是执行以下操作,一切正常:
private void textBoxGroupLayers_TextChanged(object sender, TextChangedEventArgs e)
{
this.listViewGroupLayers.Items.Filter = UserFilter;
}
但这对我来说似乎很脏。我的问题:为什么第一次调用后过滤器不工作?我检查了的实例,this.listViewGroupLayers.Items
它总是有过滤器对象。