绑定到DataVM中的SelectedItems或MVVM中的ListBox

在底部看到我的答案

只是在WPF上做一些轻量级阅读,我需要从DataGrid绑定selectedItems,但我无法想出任何有形的东西。 我只需要选定的对象。

数据网格:

 

我可以向你保证: SelectedItems确实可以绑定为XAML CommandParameter

经过大量的挖掘和谷歌搜索,我终于找到了解决这个常见问题的简单方法。

要使其工作,您必须遵循以下所有规则

  1. 根据Ed Ball的建议 ‘,在您的XAML命令数据绑定上,定义CommandParameter属性BEFORE Command属性。 这是一个非常耗时的错误。

    在此处输入图像描述

  2. 确保ICommandCanExecuteExecute方法具有对象类型的参数。 这样,您可以防止在数据绑定CommandParameter类型与命令方法的参数类型不匹配时发生的静默强制转换exception。

    private bool OnDeleteSelectedItemsCanExecute(object SelectedItems)
    {

      // Your goes heres 

    }

    private bool OnDeleteSelectedItemsExecute(object SelectedItems)
    {

      // Your goes heres 

    }

例如,您可以将listview / listbox的SelectedItems属性发送给ICommand方法,也可以将listview / listbox发送给它自己。 好的,不是吗?

希望它可以防止有人花费我大量的时间来弄清楚如何接收SelectedItems作为CanExecute参数。

我原来的答案是错误的(你不能绑定到SelectedItems因为它是一个只读属性)。

一个相当MVVM友好的解决方法是绑定到DataGridRowIsSelected属性。

您可以像这样设置绑定:

      

然后,您需要创建一个inheritance自ViewModelBase (或您正在使用的任何MVVM基类)的Document并具有您希望在DataGrid中呈现的Document的属性,以及IsSelected属性。

然后,在主视图模型中,创建一个名为DocumentViewModelsList(Of DocumentViewModel)以将DataGrid绑定到。 (注意:如果要添加/删除列表中的项目,请改用ObservableCollection(T) 。)

现在,这是棘手的部分。 您需要挂钩列表中每个DocumentViewModelPropertyChanged事件,如下所示:

 For Each documentViewModel As DocumentViewModel In DocumentViewModels documentViewModel.PropertyChanged += DocumentViewModel_PropertyChanged Next 

这允许您响应任何DocumentViewModel更改。

最后,在DocumentViewModel_PropertyChanged ,您可以遍历列表(或使用Linq查询)来获取IsSelected = True每个项目的信息。

通过一些技巧,您可以扩展DataGrid以创建SelectedItems属性的可绑定版本。 我的解决方案要求绑定具有Mode=OneWayToSource因为我只想从属性中读取,但是可以扩展我的解决方案以允许该属性是读写的。

我假设类似的技术可以用于ListBox,但我还没有尝试过。

 public class BindableMultiSelectDataGrid : DataGrid { public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IList), typeof(BindableMultiSelectDataGrid), new PropertyMetadata(default(IList))); public new IList SelectedItems { get { return (IList)GetValue(SelectedItemsProperty); } set { throw new Exception("This property is read-only. To bind to it you must use 'Mode=OneWayToSource'."); } } protected override void OnSelectionChanged(SelectionChangedEventArgs e) { base.OnSelectionChanged(e); SetValue(SelectedItemsProperty, base.SelectedItems); } } 

我知道这篇文章有点老了,已经回答了。 但我想出了一个非MVVM的答案。 它很容易,对我有用。 添加另一个DataGrid,假设您的Selected Collection是SelectedResults:

   

在后面的代码中,将其添加到构造函数:

  public ClassConstructor() { InitializeComponent(); OriginalGrid.SelectionChanged -= OriginalGrid_SelectionChanged; OriginalGrid.SelectionChanged += OriginalGrid_SelectionChanged; } private void OriginalGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { SelectedGridRows.ItemsSource = OriginalGrid.SelectedItems; } 

我来到这里寻找答案,我得到了很多很棒的答案。 我将它们全部组合成一个附属的属性,非常类似于Omar提供的属性,但是在一个类中。 处理INotifyCollectionChanged并将列表切换出来。 不泄漏事件。 我写了它,所以这将是非常简单的代码。 用C#编写,处理listbox selectedItems和dataGrid selectedItems。

这适用于DataGrid和ListBox。

(我刚学会了如何使用GitHub)GitHub https://github.com/ParrhesiaJoe/SelectedItemsAttachedWpf

使用方法:

   

这是代码。 Git上有一些小样本。

 public class Ex : DependencyObject { public static readonly DependencyProperty IsSubscribedToSelectionChangedProperty = DependencyProperty.RegisterAttached( "IsSubscribedToSelectionChanged", typeof(bool), typeof(Ex), new PropertyMetadata(default(bool))); public static void SetIsSubscribedToSelectionChanged(DependencyObject element, bool value) { element.SetValue(IsSubscribedToSelectionChangedProperty, value); } public static bool GetIsSubscribedToSelectionChanged(DependencyObject element) { return (bool)element.GetValue(IsSubscribedToSelectionChangedProperty); } public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached( "SelectedItems", typeof(IList), typeof(Ex), new PropertyMetadata(default(IList), OnSelectedItemsChanged)); public static void SetSelectedItems(DependencyObject element, IList value) { element.SetValue(SelectedItemsProperty, value); } public static IList GetSelectedItems(DependencyObject element) { return (IList)element.GetValue(SelectedItemsProperty); } ///  /// Attaches a list or observable collection to the grid or listbox, syncing both lists (one way sync for simple lists). ///  /// The DataGrid or ListBox /// The list to sync to. private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is ListBox || d is MultiSelector)) throw new ArgumentException("Somehow this got attached to an object I don't support. ListBoxes and Multiselectors (DataGrid), people. Geesh =P!"); var selector = (Selector)d; var oldList = e.OldValue as IList; if (oldList != null) { var obs = oldList as INotifyCollectionChanged; if (obs != null) { obs.CollectionChanged -= OnCollectionChanged; } // If we're orphaned, disconnect lb/dg events. if (e.NewValue == null) { selector.SelectionChanged -= OnSelectorSelectionChanged; SetIsSubscribedToSelectionChanged(selector, false); } } var newList = (IList)e.NewValue; if (newList != null) { var obs = newList as INotifyCollectionChanged; if (obs != null) { obs.CollectionChanged += OnCollectionChanged; } PushCollectionDataToSelectedItems(newList, selector); var isSubscribed = GetIsSubscribedToSelectionChanged(selector); if (!isSubscribed) { selector.SelectionChanged += OnSelectorSelectionChanged; SetIsSubscribedToSelectionChanged(selector, true); } } } ///  /// Initially set the selected items to the items in the newly connected collection, /// unless the new collection has no selected items and the listbox/grid does, in which case /// the flow is reversed. The data holder sets the state. If both sides hold data, then the /// bound IList wins and dominates the helpless wpf control. ///  /// The list to sync to /// The grid or listbox private static void PushCollectionDataToSelectedItems(IList obs, DependencyObject selector) { var listBox = selector as ListBox; if (listBox != null) { if (obs.Count > 0) { listBox.SelectedItems.Clear(); foreach (var ob in obs) { listBox.SelectedItems.Add(ob); } } else { foreach (var ob in listBox.SelectedItems) { obs.Add(ob); } } return; } // Maybe other things will use the multiselector base... who knows =P var grid = selector as MultiSelector; if (grid != null) { if (obs.Count > 0) { grid.SelectedItems.Clear(); foreach (var ob in obs) { grid.SelectedItems.Add(ob); } } else { foreach (var ob in grid.SelectedItems) { obs.Add(ob); } } return; } throw new ArgumentException("Somehow this got attached to an object I don't support. ListBoxes and Multiselectors (DataGrid), people. Geesh =P!"); } ///  /// When the listbox or grid fires a selectionChanged even, we update the attached list to /// match it. ///  /// The listbox or grid /// Items added and removed. private static void OnSelectorSelectionChanged(object sender, SelectionChangedEventArgs e) { var dep = (DependencyObject)sender; var items = GetSelectedItems(dep); var col = items as INotifyCollectionChanged; // Remove the events so we don't fire back and forth, then re-add them. if (col != null) col.CollectionChanged -= OnCollectionChanged; foreach (var oldItem in e.RemovedItems) items.Remove(oldItem); foreach (var newItem in e.AddedItems) items.Add(newItem); if (col != null) col.CollectionChanged += OnCollectionChanged; } ///  /// When the attached object implements INotifyCollectionChanged, the attached listbox /// or grid will have its selectedItems adjusted by this handler. ///  /// The listbox or grid /// The added and removed items private static void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // Push the changes to the selected item. var listbox = sender as ListBox; if (listbox != null) { listbox.SelectionChanged -= OnSelectorSelectionChanged; if (e.Action == NotifyCollectionChangedAction.Reset) listbox.SelectedItems.Clear(); else { foreach (var oldItem in e.OldItems) listbox.SelectedItems.Remove(oldItem); foreach (var newItem in e.NewItems) listbox.SelectedItems.Add(newItem); } listbox.SelectionChanged += OnSelectorSelectionChanged; } var grid = sender as MultiSelector; if (grid != null) { grid.SelectionChanged -= OnSelectorSelectionChanged; if (e.Action == NotifyCollectionChangedAction.Reset) grid.SelectedItems.Clear(); else { foreach (var oldItem in e.OldItems) grid.SelectedItems.Remove(oldItem); foreach (var newItem in e.NewItems) grid.SelectedItems.Add(newItem); } grid.SelectionChanged += OnSelectorSelectionChanged; } } } 

这将有效:

MultiSelectorBehaviours.vb

 Imports System.Collections Imports System.Windows Imports System.Windows.Controls.Primitives Imports System.Windows.Controls Imports System Public NotInheritable Class MultiSelectorBehaviours Private Sub New() End Sub Public Shared ReadOnly SynchronizedSelectedItems As DependencyProperty = _ DependencyProperty.RegisterAttached("SynchronizedSelectedItems", GetType(IList), GetType(MultiSelectorBehaviours), New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnSynchronizedSelectedItemsChanged))) Private Shared ReadOnly SynchronizationManagerProperty As DependencyProperty = DependencyProperty.RegisterAttached("SynchronizationManager", GetType(SynchronizationManager), GetType(MultiSelectorBehaviours), New PropertyMetadata(Nothing)) '''  ''' Gets the synchronized selected items. '''  ''' The dependency object. ''' The list that is acting as the sync list. Public Shared Function GetSynchronizedSelectedItems(ByVal dependencyObject As DependencyObject) As IList Return DirectCast(dependencyObject.GetValue(SynchronizedSelectedItems), IList) End Function '''  ''' Sets the synchronized selected items. '''  ''' The dependency object. ''' The value to be set as synchronized items. Public Shared Sub SetSynchronizedSelectedItems(ByVal dependencyObject As DependencyObject, ByVal value As IList) dependencyObject.SetValue(SynchronizedSelectedItems, value) End Sub Private Shared Function GetSynchronizationManager(ByVal dependencyObject As DependencyObject) As SynchronizationManager Return DirectCast(dependencyObject.GetValue(SynchronizationManagerProperty), SynchronizationManager) End Function Private Shared Sub SetSynchronizationManager(ByVal dependencyObject As DependencyObject, ByVal value As SynchronizationManager) dependencyObject.SetValue(SynchronizationManagerProperty, value) End Sub Private Shared Sub OnSynchronizedSelectedItemsChanged(ByVal dependencyObject As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) If e.OldValue IsNot Nothing Then Dim synchronizer As SynchronizationManager = GetSynchronizationManager(dependencyObject) synchronizer.StopSynchronizing() SetSynchronizationManager(dependencyObject, Nothing) End If Dim list As IList = TryCast(e.NewValue, IList) Dim selector As Selector = TryCast(dependencyObject, Selector) ' check that this property is an IList, and that it is being set on a ListBox If list IsNot Nothing AndAlso selector IsNot Nothing Then Dim synchronizer As SynchronizationManager = GetSynchronizationManager(dependencyObject) If synchronizer Is Nothing Then synchronizer = New SynchronizationManager(selector) SetSynchronizationManager(dependencyObject, synchronizer) End If synchronizer.StartSynchronizingList() End If End Sub '''  ''' A synchronization manager. '''  Private Class SynchronizationManager Private ReadOnly _multiSelector As Selector Private _synchronizer As TwoListSynchronizer '''  ''' Initializes a new instance of the  class. '''  ''' The selector. Friend Sub New(ByVal selector As Selector) _multiSelector = selector End Sub '''  ''' Starts synchronizing the list. '''  Public Sub StartSynchronizingList() Dim list As IList = GetSynchronizedSelectedItems(_multiSelector) If list IsNot Nothing Then _synchronizer = New TwoListSynchronizer(GetSelectedItemsCollection(_multiSelector), list) _synchronizer.StartSynchronizing() End If End Sub '''  ''' Stops synchronizing the list. '''  Public Sub StopSynchronizing() _synchronizer.StopSynchronizing() End Sub Public Shared Function GetSelectedItemsCollection(ByVal selector As Selector) As IList If TypeOf selector Is MultiSelector Then Return TryCast(selector, MultiSelector).SelectedItems ElseIf TypeOf selector Is ListBox Then Return TryCast(selector, ListBox).SelectedItems Else Throw New InvalidOperationException("Target object has no SelectedItems property to bind.") End If End Function End Class End Class 

IListItemConverter.vb

 '''  ''' Converts items in the Master list to Items in the target list, and back again. '''  Public Interface IListItemConverter '''  ''' Converts the specified master list item. '''  ''' The master list item. ''' The result of the conversion. Function Convert(ByVal masterListItem As Object) As Object '''  ''' Converts the specified target list item. '''  ''' The target list item. ''' The result of the conversion. Function ConvertBack(ByVal targetListItem As Object) As Object End Interface 

TwoListSynchronizer.vb

 Imports System.Collections Imports System.Collections.Specialized Imports System.Linq Imports System.Windows '''  ''' Keeps two lists synchronized. '''  Public Class TwoListSynchronizer Implements IWeakEventListener Private Shared ReadOnly DefaultConverter As IListItemConverter = New DoNothingListItemConverter() Private ReadOnly _masterList As IList Private ReadOnly _masterTargetConverter As IListItemConverter Private ReadOnly _targetList As IList '''  ''' Initializes a new instance of the  class. '''  ''' The master list. ''' The target list. ''' The master-target converter. Public Sub New(ByVal masterList As IList, ByVal targetList As IList, ByVal masterTargetConverter As IListItemConverter) _masterList = masterList _targetList = targetList _masterTargetConverter = masterTargetConverter End Sub '''  ''' Initializes a new instance of the  class. '''  ''' The master list. ''' The target list. Public Sub New(ByVal masterList As IList, ByVal targetList As IList) Me.New(masterList, targetList, DefaultConverter) End Sub Private Delegate Sub ChangeListAction(ByVal list As IList, ByVal e As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) '''  ''' Starts synchronizing the lists. '''  Public Sub StartSynchronizing() ListenForChangeEvents(_masterList) ListenForChangeEvents(_targetList) ' Update the Target list from the Master list SetListValuesFromSource(_masterList, _targetList, AddressOf ConvertFromMasterToTarget) ' In some cases the target list might have its own view on which items should included: ' so update the master list from the target list ' (This is the case with a ListBox SelectedItems collection: only items from the ItemsSource can be included in SelectedItems) If Not TargetAndMasterCollectionsAreEqual() Then SetListValuesFromSource(_targetList, _masterList, AddressOf ConvertFromTargetToMaster) End If End Sub '''  ''' Stop synchronizing the lists. '''  Public Sub StopSynchronizing() StopListeningForChangeEvents(_masterList) StopListeningForChangeEvents(_targetList) End Sub '''  ''' Receives events from the centralized event manager. '''  ''' The type of the  calling this method. ''' Object that originated the event. ''' Event data. '''  ''' true if the listener handled the event. It is considered an error by the  handling in WPF to register a listener for an event that the listener does not handle. Regardless, the method should return false if it receives an event that it does not recognize or handle. '''  Public Function ReceiveWeakEvent(ByVal managerType As Type, ByVal sender As Object, ByVal e As EventArgs) As Boolean Implements System.Windows.IWeakEventListener.ReceiveWeakEvent HandleCollectionChanged(TryCast(sender, IList), TryCast(e, NotifyCollectionChangedEventArgs)) Return True End Function '''  ''' Listens for change events on a list. '''  ''' The list to listen to. Protected Sub ListenForChangeEvents(ByVal list As IList) If TypeOf list Is INotifyCollectionChanged Then CollectionChangedEventManager.AddListener(TryCast(list, INotifyCollectionChanged), Me) End If End Sub '''  ''' Stops listening for change events. '''  ''' The list to stop listening to. Protected Sub StopListeningForChangeEvents(ByVal list As IList) If TypeOf list Is INotifyCollectionChanged Then CollectionChangedEventManager.RemoveListener(TryCast(list, INotifyCollectionChanged), Me) End If End Sub Private Sub AddItems(ByVal list As IList, ByVal e As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) Dim itemCount As Integer = e.NewItems.Count For i As Integer = 0 To itemCount - 1 Dim insertionPoint As Integer = e.NewStartingIndex + i If insertionPoint > list.Count Then list.Add(converter(e.NewItems(i))) Else list.Insert(insertionPoint, converter(e.NewItems(i))) End If Next End Sub Private Function ConvertFromMasterToTarget(ByVal masterListItem As Object) As Object Return If(_masterTargetConverter Is Nothing, masterListItem, _masterTargetConverter.Convert(masterListItem)) End Function Private Function ConvertFromTargetToMaster(ByVal targetListItem As Object) As Object Return If(_masterTargetConverter Is Nothing, targetListItem, _masterTargetConverter.ConvertBack(targetListItem)) End Function Private Sub HandleCollectionChanged(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs) Dim sourceList As IList = TryCast(sender, IList) Select Case e.Action Case NotifyCollectionChangedAction.Add PerformActionOnAllLists(AddressOf AddItems, sourceList, e) Exit Select Case NotifyCollectionChangedAction.Move PerformActionOnAllLists(AddressOf MoveItems, sourceList, e) Exit Select Case NotifyCollectionChangedAction.Remove PerformActionOnAllLists(AddressOf RemoveItems, sourceList, e) Exit Select Case NotifyCollectionChangedAction.Replace PerformActionOnAllLists(AddressOf ReplaceItems, sourceList, e) Exit Select Case NotifyCollectionChangedAction.Reset UpdateListsFromSource(TryCast(sender, IList)) Exit Select Case Else Exit Select End Select End Sub Private Sub MoveItems(ByVal list As IList, ByVal e As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) RemoveItems(list, e, converter) AddItems(list, e, converter) End Sub Private Sub PerformActionOnAllLists(ByVal action As ChangeListAction, ByVal sourceList As IList, ByVal collectionChangedArgs As NotifyCollectionChangedEventArgs) If sourceList Is _masterList Then PerformActionOnList(_targetList, action, collectionChangedArgs, AddressOf ConvertFromMasterToTarget) Else PerformActionOnList(_masterList, action, collectionChangedArgs, AddressOf ConvertFromTargetToMaster) End If End Sub Private Sub PerformActionOnList(ByVal list As IList, ByVal action As ChangeListAction, ByVal collectionChangedArgs As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) StopListeningForChangeEvents(list) action(list, collectionChangedArgs, converter) ListenForChangeEvents(list) End Sub Private Sub RemoveItems(ByVal list As IList, ByVal e As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) Dim itemCount As Integer = e.OldItems.Count ' for the number of items being removed, remove the item from the Old Starting Index ' (this will cause following items to be shifted down to fill the hole). For i As Integer = 0 To itemCount - 1 list.RemoveAt(e.OldStartingIndex) Next End Sub Private Sub ReplaceItems(ByVal list As IList, ByVal e As NotifyCollectionChangedEventArgs, ByVal converter As Converter(Of Object, Object)) RemoveItems(list, e, converter) AddItems(list, e, converter) End Sub Private Sub SetListValuesFromSource(ByVal sourceList As IList, ByVal targetList As IList, ByVal converter As Converter(Of Object, Object)) StopListeningForChangeEvents(targetList) targetList.Clear() For Each o As Object In sourceList targetList.Add(converter(o)) Next ListenForChangeEvents(targetList) End Sub Private Function TargetAndMasterCollectionsAreEqual() As Boolean Return _masterList.Cast(Of Object)().SequenceEqual(_targetList.Cast(Of Object)().[Select](Function(item) ConvertFromTargetToMaster(item))) End Function '''  ''' Makes sure that all synchronized lists have the same values as the source list. '''  ''' The source list. Private Sub UpdateListsFromSource(ByVal sourceList As IList) If sourceList Is _masterList Then SetListValuesFromSource(_masterList, _targetList, AddressOf ConvertFromMasterToTarget) Else SetListValuesFromSource(_targetList, _masterList, AddressOf ConvertFromTargetToMaster) End If End Sub '''  ''' An implementation that does nothing in the conversions. '''  Friend Class DoNothingListItemConverter Implements IListItemConverter '''  ''' Converts the specified master list item. '''  ''' The master list item. ''' The result of the conversion. Public Function Convert(ByVal masterListItem As Object) As Object Implements IListItemConverter.Convert Return masterListItem End Function '''  ''' Converts the specified target list item. '''  ''' The target list item. ''' The result of the conversion. Public Function ConvertBack(ByVal targetListItem As Object) As Object Implements IListItemConverter.ConvertBack Return targetListItem End Function End Class End Class 

那么对于XAML:

  

最后是VM:

 Public ReadOnly Property SelectedResults As ObservableCollection(Of StatisticsResultModel) Get Return _objSelectedResults End Get End Property 

信用转到: http : //blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html

我有一个解决方案,使用适合我的需求的解决方法。

在MouseUp上的listitemtemplate上创建一个事件命令,并作为commandParameter发送SelectedItems集合

       

这样,您可以在viewmodel中使用一个处理此命令的命令,或者保存所选项目以供以后使用。 玩得开心编码

对我来说,最简单的方法是在SelectionChanged事件中填充ViewModel属性。

 private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { (DataContext as MyViewModel).SelectedItems.Clear(); foreach (var i in MyDataGrid.SelectedItems) (DataContext as MyViewModel).SelectedItems.Add(i as ItemType); } 

devuxer提到的解决方案

    

具有大型数据集时不起作用。 您将需要禁用行虚拟化,这正是您需要它的情况……

EnableRowVirtualization = “假”