Search code examples
xamarin.formsxamarin-forms-4

Passing the search term from SearchHandler to ContentPage in Xamarin Forms 4


I'm trying to make use of the new SearchHandler implemented as part of Xamarin Forms 4. I've found it pretty easy so far to get suggestions populated but now I want to raise an event, or follow the suggested method of handling when a search is confirmed.

public class FoodSearchHandler: SearchHandler
{
    IFoodDataStore dataStore = new FoodDataStore();

    protected override void OnQueryConfirmed()
    {
        base.OnQueryConfirmed();
        // What to do here?
    }

    protected override void OnQueryChanged(string oldValue, string newValue)
    {
        base.OnQueryChanged(oldValue, newValue);

        if(!string.IsNullOrWhiteSpace(newValue)
        {
            // Populate suggestions
            ItemsSource = dataStore.GetSuggestions(newValue);
        }
        else
        {
            ItemsSource = null;
        } 
    }
}

public partial class FoodsPage : ContentPage
{
    ObservableCollection<Food> Foods = new ObservableCollection<Food>();

    public ItemsPage()
    {
        InitializeComponent();

        // Wire up the search handler
        Shell.SetSearchHandler(this, new FoodSearchHandler());
        BindingContext = this;
    }
}

Unfortunately, althought the alpha docs mention the search handler they don't contain any details on how to use it and the sample apps only demonstrate populating the suggestions.

Does anyone out there have a pointer to offer on how I should be notifying my ContentPage that my SearchHandler confirmed a search?


Solution

  • So, after reading the Shell docs some more, it seems what I want to do in this situation is use of Shell's new Navigation and navigate to a route passing the search text as a query, for example:

    protected override void OnQueryConfirmed()
    {
        base.OnQueryConfirmed();
    
        var shell = Application.Current.MainPage as Shell;
        shell.GoToAsync($"app:///fructika/search?query={Query}", true);
    }
    

    N.B. It doesn't look like passing data works right now or if it does I'm doing it wrong but I'll raise a separate question about that.