2

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!

Community
  • 1
  • 1
mohammadmot
  • 135
  • 2
  • 12

2 Answers2

5

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();
        }
    }
Kylo Ren
  • 8,551
  • 6
  • 41
  • 66
1

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);
            }
        }
    }
Anton
  • 718
  • 6
  • 11