title: Keeping Focus/SelectedItem after DataGrid ItemsSource change
body: <p>ive been working on this for a few days, but cant seem to come up with a solution</p>
  
  <p>i have code on a timer that refreshes the <code>DataGrid</code> every few seconds</p>
  
  <p>i tried many refresh options, but in the end they all lose the users focus and sometimes also the <code>SelectedItem</code></p>
  
  <p>heres my code:</p>
  
  <pre class="lang-vb prettyprint-override"><code>        AddHandler bw.RunWorkerCompleted, Function(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs)
                                                Dim lst = e.Result
                                                Dim lst2 = CType(lst, List(Of Object)).OfType(Of INotifyPropertyChanged)()
                                                'If Items.Count = 0 Then
                                                Dim a = SelectedItem
                                                Collection.Clear()
                                                Collection.AddRange(lst2)
                                                SelectedItem = a
                                                'ItemsSource = lst
                                                'End If
                                                'For Each rw In lst
                                                '    Dim mtch = Collection.Where(Function(x) x.GetHashCode = rw.GetHashCode)
  
                                                'Next
  </code></pre>
  
  <p>i left the comments so you can see the different approaches i tried</p>
  
  <p><strong>RESULTS:</strong></p>
  
  <p>if i directly set the <code>ItemsSource</code> with the result (as in the comment), then the <code>SelectedItem</code> and the <code>Keyboard.FocusedElement</code> keep steady till the end of the above code, but somewhere between the end of this code and the next tick they are both turned into <code>Nothing</code></p>
  
  <p>if i go with the <code>ObservableCollection</code> then <code>SelectedItem</code> is lost as soon as i clear the collection and <code>Keyboard.FocusedElement</code> is only lost sometime between ticks. though the SelectedItem can be retained here with a temp backing variable</p>
  
  <p>so the point is how do we refresh the items from the db while still keeping (most-importantly) the keyboard focus</p>
  
  <p>and yes, i know that <code>ObservableCollections</code> are not "made" to be reset. in fact, im not really interested in using one. it just has one plus of keeping the <code>SelectedItem</code></p>
  
  <p>P.S. i also tried hooking into several events (<code>OnItemsSourceChanged</code>,<code>SourceUpdated</code>...) but they weren't fired at the right time, or didnt fire at all</p>
  
  <p>any ideas?</p>
  
  <p>id really most appreciate</p>
  
  <p>thank you</p>