How to perform search in Xamarin.Forms SfPicker
The Xamarin.Forms SfPicker allows to perform search to bring the items to view when we have a large list of items by customizing the picker header. For example, in this sample, we have added an entry in Xamarin.Forms SfPicker as a custom header. Using the TextChanged event in entry, you can search the items based on entry text.
The following steps explain how to perform search in Xamarin.Forms SfPicker header.
Step 1: Create a symbol view model class and add items that need to be displayed in Xamarin.Forms SfPicker.
Step 2: Add the SfPicker in XAML page and add entry view to HeaderView to perform search in Xamarin.Forms SfPicker.
Step 3: Get the entry text and set the value of entry text to the SelectedItem property of Xamarin.Forms SfPicker using the entry text changed event. If the entered text is available in picker items, then it will be selected in Xamarin.Forms SfPicker.
XAML:
<ContentPage.BindingContext> <local:ColorInfo x:Name="colorInfo"/> </ContentPage.BindingContext> <ContentPage.Content> <picker:SfPicker x:Name="picker" PickerHeight="350" PickerWidth="250" ItemsSource="{Binding ColorItems}" SelectionChanged="Picker_SelectionChanged"> <picker:SfPicker.HeaderView> <Entry x:Name="entry" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="Center" Placeholder="Enter a color name" TextChanged="Entry_TextChanged"/> </picker:SfPicker.HeaderView> </picker:SfPicker> </ContentPage.Content>
The following code sample demonstrates how to customize the entry text changed event and how to set entry text to the selected item property in Xamarin.Forms SfPicker.
C#:
private void Entry_TextChanged(object sender, TextChangedEventArgs e) { for (int i = 0; i < colorInfo.ColorItems.Count; i++) { if (e.NewTextValue == colorInfo.ColorItems[i].ToString()) { picker.SelectedItem = e.NewTextValue; } } }
Output:
You can download the sample from this link: Sample