简体   繁体   中英

How to bind CollectionView SelectedItems to a List?

I have a CollectionView and which consists of a list of items. I can't figure out a way to bind the multiple selected items to a list in the ViewModel.

XAML Code:

<CollectionView ItemsSource="{Binding Names}" SelectedItems="{Binding NamesSelection}" SelectionMode="Multiple">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Label Text="{Binding Name}" VerticalOptions="Center"/>
            </StackLayout>
         </DataTemplate>
     </CollectionView.ItemTemplate>
</CollectionView>

Nonfunctional ViewModel Code:

public MvxObservableCollection<Name> Names { get; } = new MvxObservableCollection<Name>(NamesHelpers.GetObjects());
private MvxObservableCollection<Name> _namesSelection;
public MvxObservableCollection<Name> NamesSelection 
{ 
    get=> _namesSelection;
    set 
    {
         SetProperty(ref _namesSelection, value);
    } 
}

This would probably work if I had a SelectedItem clause. But I'm not sure how to get it working for SelectedItems.

Ideal output would be for the NamesSelection List to populate/depopulate based on the selected items.

尝试将 NamesSelection 设为 ObservableCollection 或与 Names 相同 => MvxObservableCollection 检查此处多预选

NamesSelection ( List ) and Names ( MvxObservableCollection ) need to be the same collection type, so either do:

private MvxObservableCollection<string> _namesSelection;
public MvxObservableCollection<string> NamesSelection
{ 
    get=> _namesSelection;
    set 
    {
        SetProperty(ref _namesSelection, value);
    } 
}

Or

List<string> Names { get; }

In my opinion, I recommend using List<T> or ObservableCollection<T> , since they are the most common types of collection objects, MvxObservableCollection may not be supported by CollectionView or can cause some issues

SelectedItems must be an IList<object> . ObservableCollection<object> does not implement that interface (nor does eg. List<Name> , due to covariance) , so that will not work.

The workaround is to bind SelectedItems to a List<object> , then subscribe to the SelectionChanged event. Then manually update the bindings when the selected items change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM