Вот прикрепленное свойство, которое подключается к событию SelectionChanged объекта ListBox и заполняет список выбранных элементов в ViewModel.Вы можете просто изменить «ListBox» на «DataGrid».
http://marlongrech.wordpress.com/2009/06/02/sync-multi-select-listbox-with-viewmodel/
Редактировать: Добавление исходного кода для версии DataGrid ...
/// <summary>
/// Attached property that stores the selected items of a DataGrid
/// </summary>
public static class DataGridService
{
#region SelectedItems
/// <summary>
/// SelectedItems Attached Dependency Property
/// </summary>
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached(
"SelectedItems",
typeof(IList),
typeof(DataGridService),
new FrameworkPropertyMetadata((IList)null, new PropertyChangedCallback(OnSelectedItemsChanged)));
/// <summary>
/// Gets the SelectedItems property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
/// <returns>The value of the SelectedItems property</returns>
public static IList GetSelectedItems(DependencyObject d)
{
return (IList)d.GetValue(SelectedItemsProperty);
}
/// <summary>
/// Sets the SelectedItems property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
/// <param name="value">value of the property</param>
public static void SetSelectedItems(DependencyObject d, IList value)
{
d.SetValue(SelectedItemsProperty, value);
}
/// <summary>
/// Handles changes to the SelectedItems property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
/// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = (DataGrid)d;
ReSetSelectedItems(grid);
grid.SelectionChanged += delegate
{
ReSetSelectedItems(grid);
};
}
/// <summary>
/// Sets the selected items collection for the specified <see cref="DataGrid"/>
/// </summary>
/// <param name="grid"><see cref="DataGrid"/> to use for setting the selected items</param>
private static void ReSetSelectedItems(DataGrid grid)
{
IList selectedItems = GetSelectedItems(grid);
selectedItems.Clear();
if (grid.SelectedItems != null)
{
foreach (var item in grid.SelectedItems)
{
selectedItems.Add(item);
}
}
}
#endregion
}
В XAML:
<tk:DataGrid ... local:DataGridService.SelectedItems="{Binding Path=MyCollection}" SelectionMode="Extended">
«MyCollection» должна быть ObservableCollection в вашей ViewModel.