I have a list view that binding items with a property in viewmodel.
<ListView Height="238"
HorizontalAlignment="Left"
Name="listView"
VerticalAlignment="Top"
Width="503"
ItemsSource="{Binding BusinessCollection}"
SelectionMode="Multiple">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding ID}" Header="ID" />
<GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
and in viewmodel.
ICollectionView _businessCollection
public ICollectionView BusinessCollection
{
get { return _businessCollection; }
set {
_businessCollection = value;
RaisePropertyOnChange("BusinessCollection");
}
}
How to get selected item of businesscollection in viewmodel?
Since the itemSource is BusinessCollection, you should be able to:
Wrap it as a property on your VM. Hope it helps!
1. One way to source binding:
You have to use
SelectionChanged
event. The easiest way is to write eventhandler in codebehind to "bind selecteditems" to viewmodel.This still aligns with MVVM design, because view and viewmodel resposibilities are kept separated. You dont have any logic in codebehind and viewmodel is clean and testable.
2. Two way binding:
if you also need to update view, when viewmodel changes, you have to attach to ViewModel's
PropertyChanged
event and to the selected items'CollectionChanged
event. of course you can do it in codebehind, but in this case I would create something more reusable:or can create custom attached property, so you can use binding syntax in xaml:
Attached property implementation