WPF ListView项目筛选器-刷新项目后未触发筛选器

时间:2019-04-02 12:53:17

标签: c# wpf listview itemcollection

我正在尝试将过滤器添加到我的ListView。筛选器取决于来自TextBox的输入。我将过滤器添加到ListView并在TextBox Input更改时触发Refresh。我的问题:筛选器方法只调用一次。

我所拥有的:

我在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中设置了一个断点。如果我在文本框中输入第一个字母,则断点将处于活动状态,并且过滤器工作正常。但是,如果我现在输入第二个字母,则不会调用过滤器。

如果我仅执行以下操作,则一切正常:

        private void textBoxGroupLayers_TextChanged(object sender, TextChangedEventArgs e)
    { 
        this.listViewGroupLayers.Items.Filter = UserFilter;     
    }

但这对我来说似乎很肮脏。 我的问题: 为什么在第一次调用后过滤器不工作? 我检查了this.listViewGroupLayers.Items的实例,它始终具有过滤器对象。

0 个答案:

没有答案
相关问题