ive been working on this for a few days, but cant seem to come up with a solution
i have code on a timer that refreshes the DataGrid
every few seconds
i tried many refresh options, but in the end they all lose the users focus and sometimes also the SelectedItem
heres my 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
i left the comments so you can see the different approaches i tried
RESULTS:
if i directly set the ItemsSource
with the result (as in the comment), then the SelectedItem
and the Keyboard.FocusedElement
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 Nothing
if i go with the ObservableCollection
then SelectedItem
is lost as soon as i clear the collection and Keyboard.FocusedElement
is only lost sometime between ticks. though the SelectedItem can be retained here with a temp backing variable
so the point is how do we refresh the items from the db while still keeping (most-importantly) the keyboard focus
and yes, i know that ObservableCollections
are not "made" to be reset. in fact, im not really interested in using one. it just has one plus of keeping the SelectedItem
P.S. i also tried hooking into several events (OnItemsSourceChanged
,SourceUpdated
...) but they weren't fired at the right time, or didnt fire at all
any ideas?
id really most appreciate
thank you
You need to use the SelectedIndex instead of the SelectedItem property of the DataGrid. Save the selected index before replacing ItemsSource with lst.
The reason SelectedItem does not work is that this is a reference to an object in the list you are replacing.
Perhaps you don't want to use index because the focused item might move up or down based on database update. In that case you will need to use the key to find the index of the record in the new list.
If you can't use the index or don't have a key then I can't think of a good way to do this.
Also it seems to me that replacing the list completely will lead to other problems. If the user is typing something into DataGrid cell and you replace the list under them, they will lose their edits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With