How to set ItemSelected to null after selection (Xamarin Shell Search Handler)

iooovoltsiooovolts Member ✭✭✭

I am using SearchHandler component in an application I am using as a way to populate a list of items based on a selection from the dropdown.
The problem I am having is that if I select for example Item 1 from the search dropdown and I add it to my list, I cannot add it again.
I can add other items, and then I can add Item 1 again. So it seems to me like after selecting Item 1 it is selected and cannot be re-selected, it is the only logical assumption. If someone has a solution to this it would be really helpful for me. My code is below:

Front-end (XAML)

<Shell.SearchHandler>
    <SearchHandler ShowsResults="true"
                   Query="{Binding Query}"
                   Placeholder="Search ingredient..."
                   ItemsSource="{Binding Items, Mode=TwoWay}"
                   SelectedItem="{Binding Item, Mode=TwoWay}">
        <SearchHandler.ItemTemplate>
            <DataTemplate>
                <Grid Padding="10">
                    <Label Text="{Binding Name}"
                           FontAttributes="Bold"/>
                </Grid>
            </DataTemplate>
        </SearchHandler.ItemTemplate>
    </SearchHandler>
</Shell.SearchHandler>

View-model (C#)

private Item _item;
public Item Item
{
    get => _item;
    set
    {
        if (value != null)
        {
            var userItem = MapItemToUserItem(value as Item);
            AddUserItem(userItem);
        }
    }
}

private UserItem MapItemToUserItem(Item item)
{
    return new UserItem
    {
        Name = item.Name
    };
}

private async void AddUserItem(UserItem userItem)
{
    await _unitOfWork.UserItemRepository.AddAsync(userItem);
    var result = await _unitOfWork.CompleteAsync();

    if (result == 1)
        UserItems.Add(userItem);
}

Basically, after I try and add an item the second time. It never hits the set statement. Thanks in advance Xamarin buddies :smile:

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited July 22

    You can try to change the binding mode from the TwoWay to OneWay. And you can refer to this SearchHandler https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/search#create-a-searchhandler

  • iooovoltsiooovolts Member ✭✭✭

    @LeonLu I have tried all binding modes already, unfortunately OneWay does not work as the setter for Item is never hit. Also the reason I have used the search handler the way I have is because I use repositories and dependency injection in my application.
    If I had a concrete implementation of a class extending SearchHandler I would have to pass a repository into the constructor to call the method which would get a list of items and populate ItemsSource of the SearchHandler. Unfortunately you cannot inject dependencies through XAML and this is why I have not done things that way.

Sign In or Register to comment.