Everything is bound nicely and everything works up to this point. However the view model has a timer running that periodically refreshes the CurrentSnapshot object. When it does, because the ViewModel implements INotifyPropertyChanged, the ItemsSource for the listview is refreshed, the new items are bound, and the existing selection is lost. Without MVVM I would likely have something like this:
Private Sub lvItems_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
_selectedSample = lvItems.SelectedItem
If _selectedSample IsNot Nothing Then
_lastSelectedMachine = _selectedSample.MachineName
_lastSelectedMachine = ""
And then I would RemoveHandler and AddHandler before and after assigning to the ItemsSource. I cannot see how I can do this while respecting the MVVM pattern however. I have seen some examples online, that suggest using an attached behavior and whatnot. Isn't there a simple and easy way to handle this without having to go dig through dependency properties?
Private _currentSnapshot As New ObservableCollection(Of KeyedPerformanceSample)
Public Property CurrentSnapshot As ObservableCollection(Of KeyedPerformanceSample)
Set(value As ObservableCollection(Of KeyedPerformanceSample))
_currentSnapshot = value
RemoveHandler CurrentSnapshotView.CurrentChanged, AddressOf CurrentSnapshotView_CurrentChanged
_currentSnapshotView = CollectionViewSource.GetDefaultView(_currentSnapshot)
AddHandler CurrentSnapshotView.CurrentChanged, AddressOf CurrentSnapshotView_CurrentChanged
Private _currentSnapshotView As ICollectionView = CollectionViewSource.GetDefaultView(CurrentSnapshot)
Public ReadOnly Property CurrentSnapshotView As ICollectionView
Public Sub CurrentSnapshotView_CurrentChanged(sender As Object, e As EventArgs)
SelectedSample = CurrentSnapshotView.CurrentItem
Private Sub ViewModel_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles Me.PropertyChanged
If e.PropertyName = "CurrentSnapshot" Then
If SelectedSample IsNot Nothing Then
Dim newSelection = CurrentSnapshot.Where(Function(x) x.Key = SelectedSample.Key).FirstOrDefault
If newSelection IsNot Nothing Then CurrentSnapshotView.MoveCurrentTo(newSelection)
So this way everything is in the ViewModel and nothing bleeds out!