How can i get all selected item(s) from ListView in ViewModel class? [closed]

只愿长相守 提交于 2020-01-07 00:25:05

问题


I wrote a program with MVVM (C#) and XAML using Caliburn.Micro library, how can I get all selected items from ListView control (not only one item)?

My code link ...

With binding method SelectedItem="{Binding SelectedItem}" just got first selected item!


回答1:


To get selected items into the ViewModel, first create a property of bool type in your model that will be bound with IsSelected property of ListViewItem.

Property in Model class:

 public bool IsSelected
    {
        get { return isSelected; }
        set 
        { 
            isSelected = value;
            RaiseChange("IsSelected");
        }
    }

XAML Style:

 <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Final Property in ViewModel:

 public List<DataGridItem> SelectedItem
    {
        get
        {
            return list.Where(item=>item.IsSelected).ToList();
        }
    }



回答2:


Keep calm and see example on github :) https://github.com/samueldjack/SelectedItemsBindingDemo/blob/master/MultiSelectorBehaviours.cs

This example based on using behaviours.
It is powerfull approach which can resolve many problem in MVVM.

You need 3 files from example: IListeItemConverter.cs, MultiSelectorBehaviour.cs, TwoListSynchronizer.cs. Copy it to your project.

then you must define namespace in your view

xmlns:conv="clr-namespace:[MultiSelectorBehavourNamespace]"

after it you can use MultiSelectorBehaviour in ListView

<ListView DockPanel.Dock="Top" conv:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding SelectedItems}"/>

course you need also define SourceItems property in your ViewModel

private ObservableCollection<YourItemType> selectedItems = new ObservableCollection<YourItemType>();
    public ObservableCollection<YourItemType> SelectedItems
    {
        get { return selectedItems; }
        set
        {
            if (selectedItems != value)
            {
                selectedItems = value;
                RaisePropertyChanged(() => SelectedItems);
            }
        }
    }


来源:https://stackoverflow.com/questions/35339524/how-can-i-get-all-selected-items-from-listview-in-viewmodel-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!