I'm using the WPF Toolkit's DataGrid. I've enabled the property on the DataGrid to allow for multi-selecting of rows. How do I get the SelectedItems out? I'm using an MVVM framework to bind my ViewModel to my View.
Thanks!
I'm using the WPF Toolkit's DataGrid. I've enabled the property on the DataGrid to allow for multi-selecting of rows. How do I get the SelectedItems out? I'm using an MVVM framework to bind my ViewModel to my View.
Thanks!
Hi Shafique,
I've been looking for an answer to this question as well. The answers that I have found is either to 1) in the codebehind delegate the work to a method in the ViewModel passing the SelectedItems list from the datagrid. This collection will contain all of the items that are selected - Or 2) use the MVVM toolkit light that allows you to use Event to Command and pass an object as a parameter directly to the ViewModel.
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
IList lst = this.myDataGrid.SelectedItems;
ViewModel.RowsSelected(lst);
}
In this case you will need to bind your selectionchanged in your xaml to your selectionchanged in the code behind. Then in your codebehind you can save this list and use it for Deleting selected rows, etc.
If there is a better way to do this, I'd love to know is well.
HTH
Bill
I managed to get around this using Relay Commands as Bill mentioned. It is a little dirty in parts, but I avoided putting any code in the behind file.
Firstly, in your XAML - Bind your command onto a button, or whatever triggers your RelayCommand.
<Button Content="Select"
cmd:ButtonBaseExtensions.Command="{Binding CommandSelect}"
cmd:ButtonBaseExtensions.CommandParameter="{Binding ElementName=Results, Path=SelectedItems}" />
You'll notice the command parameter Binds to another UI element - the DataGrid or ListView you wish to get the selected items of. This syntax will work in Silverlight 3 as well as WPF, as it now supports element to element binding.
In your view model your Command will look something like this
Private _CommandSelect As RelayCommand(Of IEnumerable)
Public ReadOnly Property CommandSelect() As RelayCommand(Of IEnumerable)
Get
If _CommandSelect Is Nothing Then
_CommandSelect = New RelayCommand(Of IEnumerable)(AddressOf CommandSelectExecuted, AddressOf CommandSelectCanExecute)
End If
Return _CommandSelect
End Get
End Property
Private Function CommandSelectExecuted(ByVal parameter As IEnumerable) As Boolean
For Each Item As IElectoralAreaNode In parameter
Next
Return True
End Function
Private Function CommandSelectCanExecute() As Boolean
Return True
End Function
The Selected Items will be returned as a SelectedItemCollection, but you probably don't want this dependancy in your View Model. So typing it as IEnumerable and doing a little casting is your only option, hense the 'dirtyness'. But it keeps your code behind clean and MVVM pattern in tact!