Reputation: 1441
I have a WPF DataGrid with some data bound to LINQ to SQL entity classes. One column is a clock showing a given flight's airborn time, which is calculated using logic in Flight's partial class. I have a timer calling datagrid.Items.Refresh every 2 seconds to update the clock.
The refresh works fine, but now I'm adding keyboard shortcuts. Navigating through cells with the keyboard arrows works fine with the timer off, but with the Refresh timer enabled, the focused cell (actually the entire datagrid) loses focus.
I need to either somehow maintain focus (preferred) or disable the timer whenever the DataGrid is focused. I can't even seem to get the latter to work. I've tried:
if (!dataGrid.IsFocused)
dataGrid.Items.Refresh();
and
if (!dataGrid.IsKeyboardFocused)
dataGrid.Items.Refresh();
for the timer, but these properties return false even when the datagrid is focused.
Any ideas?
Upvotes: 8
Views: 10228
Reputation: 4167
Your cells lose focus because you change the underlying collection (ItemsSource). There is no beautiful way, as far as I recall, to get the cell. For the row :
If you work with MVVM, you can memorize your SelectedItem
or SelectedIndex
and restore it after the reload is done by binding. That will get you in the right row, for a start. Both have different drawbacks:
SelectedItem
requires a bit more work. Make sure you override Equals
and GetHashCode
in the underlying objects if you use it. If your item was number 5 in the collection and during the reload another row appears before it, you will still end up in the right lineSelectedIndex
is the quickest solution, but is only a numeric position. If you select entry number 5 and the reload merges in rows before it, you will end up with the wrong selected row.As I said, I haven't tried with the cells, but you can read this for a start. Maybe you can apply it to your issue.
Upvotes: 0
Reputation: 1548
The best way is not to use dataGrid.Items.Refresh() as update mechanism. It sounds like the underlying objects are already updated separately. If they implement INotifyPropertyChanged, you should try to set the binding mode for the colum as TwoWay Binding:
<DataGridTextColumn Binding="{Binding xyz, Mode=TwoWay}"/>
Upvotes: 2
Reputation: 7419
i think you may get the present focus and after grid is refreshed give the selected cell back its focus something like
int index = 11;
myDataGrid.SelectedItem = myDataGrid.Items[index];
myDataGrid.ScrollIntoView(myDataGrid.Items[index]);
DataGridRow dgrow = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromItem(myDataGrid.Items[index]);
dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
also check this out it may help you
Upvotes: 0