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)?
With binding method SelectedItem="{Binding SelectedItem}"
just got first selected item!
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)?
With binding method SelectedItem="{Binding SelectedItem}"
just got first selected item!
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();
}
}
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);
}
}
}