How to implement Search inside of the Picker in .NET MAUI

589 views Asked by At

I am building a .NET MAUI Android application and I want to implement Search upon selecting something from a Picker (since my Picker component can have more than 100 elements of data).

Does anybody have an idea on how to implement this?

My initial idea was to try to implement Search through the SearchBar component specifically with the TextChanged event, but I had no success.

So I am wondering if is there a whole component that includes Search and the Picker, and if there isn't what do you suggest I do in order to implement search in the picker component?

2

There are 2 answers

0
Samurai_Jack_Dev On BEST ANSWER

Based on @Jason Comment I managed to resolve this by creating CollectionView with SearchBar.

0
Stephen Quan On

Building on @Jason's answer, create a view model with FilterText, Words and FilteredWords:

// MainViewModel.cs
public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(FilteredWords))]
    private string _filterText = string.Empty;

    [ObservableProperty]
    private List<string> _words
        = "the,be,to,of,and,a,in,that,have,I,it,for,not,on,with,he,as,you,do,at,this,but,his,by,from,they,we,say,her,she,or,an,will,my,one,all,would,there,their,what,so,up,out,if,about,who,get,which,go,me,when,make,can,like,time,no,just,him,know,take,people,into,year,your,good,some,could,them,see,other,than,then,now,look,only,come,its,over,think,also,back,after,use,two,how,our,work,first,well,way,even,new,want,because,any,these,give,day,most,u"
          .Split(",").ToList();

    public List<String> FilteredWords
        => FilterText.Length == 0 ? Words : Words.Where(w => w.StartsWith(FilterText)).ToList();
}

Then, on your page, create a TwoWay binding for FilteredText and show the FilteredWords in a ListView. React to ItemTapped events on the ListView.

<!-- MainPage.xaml -->
<Grid RowDefinitions="Auto,*">
    <Entry Text="{Binding FilterText, Mode=TwoWay}"/>
    <ListView Grid.Row="1"
              ItemsSource="{Binding FilteredWords}"
              ItemTapped="ListView_ItemTapped">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding .}"/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>
// MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    public MainPage(MainViewModel VM)
    {
        InitializeComponent();
        BindingContext = VM;
    }

    private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        Debug.WriteLine($"Tapped {e.Item}");
    }
}