简体   繁体   中英

Adding Filter TextBox to a ComboBox using MVVM in WPF

What I am trying to do is create a ComboBox where at the top there is a textbox that I can type into to filter the items within the ComboBox. Here is a an example of what I mean:

在此处输入图片说明

I need to do this using an MVVM approach. I am not sure how to go about this or how to overwrite the style to do so. I have looked on google for several solutions but none of them are quite exactly what I need. I am pretty sure once I have the style created I can figure out the filtering portion within my view model.

Any help would be appreciated.

ComboBox控件使用IsTextSearchEnabled ,如下所示:

<ComboBox IsTextSearchEnabled="True" IsTextSearchCaseSensitive="True or False depending on your scenario" />

In my projects, when I do something like this, I add a TextBox as the first item in the dropdown content template, with a presenter following it of the items that need to be data-bound.

 <ComboBox>
    <ComboBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
        <TextBox Text="{Binding Path=FilteredText"} Mode="TwoWay"/>
        <ListBox ItemSource="{Binding Path=ItemsForBinding}" Mode="TwoWay" NotifyOnSourceUpdated="True" />
        </StackPanel>
      </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And in your view-model, make sure that NotifyOnProperyChanged is enabled for the FilteredText property when it is updated, it will trigger the "removal" of the bound-items, I usually use ObservableCollection, but I know ListCollectionView has capabilities to filter and notifies the UI when the collection changes. You can even find a 3rd party text AutoCompleteBox ( I use Telerik,) and it would allow you to prepopulate the terms in the "textbox" that you want the user to be able to filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM