ComboBox过滤

在View中完成数据筛选,无需改变数据源的内容,这样就不必担心在其它地方也使用这个数据源。

从路由事件 TextBoxBase.TextChanged 中获取输入的文本,并设置视图的过滤器就可以了。

CollectionViewSource.GetDefaultView 方法是返回一个 ICollectionView 对象,它是给定源集合的默认视图,然后设置视图的Filter属性。

官方文档:如何:筛选视图中的数据

完整示例在我的Github

        <ComboBox Width="300" HorizontalAlignment="Center" VerticalAlignment="Center" 
                  ItemsSource="{Binding DemoCollection, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" 
                  IsEditable="True" IsTextSearchEnabled="False"
                  TextBoxBase.TextChanged="ComboBox_TextChanged"/>
        private void ComboBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is ComboBox comboBox)
            {
                var view = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);
                view.Filter = f => f is string s && s.Contains(comboBox.Text);
            }
        }

Demo运行效果图



原文地址:https://www.cnblogs.com/noctwolf/p/11153095.html