SEE MY ANSWER AT THE BOTTOM
Just doing some light reading on WPF where I need to bind the selectedItems from a DataGrid but I am unable to come up with anything tangible. I just need the selected objects.
DataGrid:
<DataGrid Grid.Row="5"
Grid.Column="0"
Grid.ColumnSpan="4"
Name="ui_dtgAgreementDocuments"
ItemsSource="{Binding Path=Documents, Mode=TwoWay}"
SelectedItem="{Binding Path=DocumentSelection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="White"
SelectionMode="Extended" Margin="2,5"
IsReadOnly="True"
CanUserAddRows="False"
CanUserReorderColumns="False"
CanUserResizeRows="False"
GridLinesVisibility="None"
HorizontalScrollBarVisibility="Hidden"
columnHeaderStyle="{StaticResource GreenTea}"
HeadersVisibility="Column"
BorderThickness="2"
BorderBrush="LightGray"
CellStyle="{StaticResource NonSelectableDataGridCellStyle}"
SelectionUnit="FullRow"
HorizontalContentAlignment="Stretch" AutoGenerateColumns="False">
My original answer was wrong (you cannot bind to
SelectedItems
because it is a read-only property).One fairly MVVM-friendly way to work around this is to bind to the
IsSelected
property ofDataGridRow
.You can set up the binding like this:
Then you need to create a
DocumentViewModel
that inherits fromViewModelBase
(or whatever MVVM base class you are using) and has the properties of yourDocument
you want to present in the DataGrid, as well as anIsSelected
property.Then, in your main view model, you create a
List(Of DocumentViewModel)
calledDocumentViewModels
to bind yourDataGrid
to. (Note: if you will be adding/removing items from the list, use anObservableCollection(T)
instead.)Now, here's the tricky part. You need to hook into the
PropertyChanged
event of eachDocumentViewModel
in your list, like this:This allows you to respond to changes in any
DocumentViewModel
.Finally, in
DocumentViewModel_PropertyChanged
, you can loop through your list (or use a Linq query) to grab the info for each item whereIsSelected = True
.What about using a converter?
Use it in a
DataGrid
'sContextMenu
like this:This will work:
MultiSelectorBehaviours.vb
IListItemConverter.vb
TwoListSynchronizer.vb
Then for the XAML:
And finally the VM:
Credit Goes to: http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html
For me the easiest route was to populate the ViewModel property in the SelectionChanged event.