There is a way that does not require disabling virtualization (which degrades performance). The problem (as mentioned in the previous answer) is that you cannot rely on ItemContainerStyle to reliably update IsSelected on all your view models, since element containers exist only for visible elements. However, you can get the full set of selected items from the ListBox SelectedItems property.
This requires a connection to the Viewmodel with the view, which is usually a no-no for violating the principles of MVVM. But there is a template so that it all works and that your ViewModel can be tested. Create a view interface for the virtual machine to talk to:
public interface IMainView { IList<MyItemViewModel> SelectedItems { get; } }
In your view model, add the View property:
public IMainView View { get; set; }
In your opinion, subscribe to OnDataContextChanged, then run this:
this.viewModel = (MainViewModel)this.DataContext; this.viewModel.View = this;
And also implement the SelectedItems property:
public IList<MyItemViewModel> SelectedItems => this.myList.SelectedItems .Cast<MyItemViewModel>() .ToList();
Then, in your view model, you can get all the selected this.View.SelectedItems elements.
When you write unit tests, you can configure IMainView to what you want.
RandomEngy Feb 03 '18 at 17:47 2018-02-03 17:47
source share