天天看點

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運作效果圖

ComboBox過濾

繼續閱讀