How to bind to autocomplete selecteditem with Obse

2019-09-04 13:16发布

问题:

I'm currently implementing autocomplete box from syncfusion. The current selection mode is set to Token

<autocomplete:SfAutoComplete x:Name="autoComplete"
                                DisplayMemberPath="Location"
                                MultiSelectMode="Token"
                                HeightRequest="120"
                                HorizontalOptions="FillAndExpand"
                                TokensWrapMode="Wrap" 
                                SelectedItem="{Binding SelectedLocation}"
                                DataSource="{Binding FilteredLocations}"                                                   
                                Text="{Binding SearchLocation, Mode=TwoWay}" >
</autocomplete:SfAutoComplete>

I'm currently using MVVM approach, how do I bind to SelectedLocation without using object base type.

private ObservableCollection<SearchItem> _filteredLocations;
public ObservableCollection<SearchItem> FilteredLocations
{
    get { return _filteredLocations; }
    set { SetProperty(ref _filteredLocations, value); }
}

What I have that current works

public object SelectedLocation
{
    get { return _selectedLocation; }
    set
    {
        SetProperty(ref _selectedLocation, value);
    }
}

But I don't want the type to be object, and what I change it to be ObservableCollection<SearchItem>, SelectedLocation is no longer picked up. May I get tips or suggestions to properly bind to the selecteditem when it's a collection.

What I tried that didn't work

public ObservableCollection<SearchItem> SelectedLocation
{
    get { return _selectedLocation; }
    set
    {
        SetProperty(ref _selectedLocation, value);
    }
}

回答1:

Edited after the clarification from OP:

It looks like you'll have to make it work by using ObservableCollection<object>. If you then want to access the individual SearchItem objects, you'll need a mechanism to call another method or property setter and cast the items there.

public ObservableCollection<object> SelectedLocation
{
    get { return _selectedLocation; }
    set
    {
        SetProperty(ref _selectedLocation, value);
    }
}

For a full example of how to use the ObservableCollection<object> and then casting the results to strings (or in your case to SearchItem), take a look at this KB article: How to get SelectedText from AutoComplete. It's not 1:1 to your use-case but should be enough to proceed.