简体   繁体   English

如何将 CollectionView SelectedItems 绑定到列表?

[英]How to bind CollectionView SelectedItems to a List?

I have a CollectionView and which consists of a list of items.我有一个 CollectionView,它包含一个项目列表。 I can't figure out a way to bind the multiple selected items to a list in the ViewModel.我想不出将多个选定项目绑定到 ViewModel 中的列表的方法。

XAML Code: XAML 代码:

<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:非功能性 ViewModel 代码:

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.如果我有 SelectedItem 子句,这可能会起作用。 But I'm not sure how to get it working for SelectedItems.但我不确定如何让它为 SelectedItems 工作。

Ideal output would be for the NamesSelection List to populate/depopulate based on the selected items.理想的输出是 NamesSelection List 根据所选项目填充/取消填充。

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

NamesSelection ( List ) and Names ( MvxObservableCollection ) need to be the same collection type, so either do: NamesSelection ( List ) 和Names ( MvxObservableCollection ) 需要是相同的集合类型,所以要么做:

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在我看来,我建议使用List<T>ObservableCollection<T> ,因为它们是最常见的集合对象类型, MvxObservableCollection可能不受CollectionView支持或可能导致一些问题

SelectedItems must be an IList<object> . SelectedItems必须是IList<object> ObservableCollection<object> does not implement that interface (nor does eg. List<Name> , due to covariance) , so that will not work. ObservableCollection<object>不实现该接口(例如List<Name> ,由于协方差) ,因此将不起作用。

The workaround is to bind SelectedItems to a List<object> , then subscribe to the SelectionChanged event.解决方法是将SelectedItems绑定到List<object> ,然后订阅SelectionChanged事件。 Then manually update the bindings when the selected items change.然后在所选项目更改时手动更新绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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