Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine who has focus in WPF Window

We are using WPF and have a window derived from a DockingLibrary. This window has a grid with multiple items in it, one being a WPF datagrid. We are using the M-V-VM pattern. When this windown is created and shown, none of the rows in this datagrid are selected. We can set the row to display as highlighted by doing something like:

  SharedWindow.ShipmentWin.shipmentDataGrid.SelectedIndex = 0;

This causes the first row in the datagrid to be shown as highlighted. But, and isn't there always one of these, this row is not Selected nor does it have Focus. I tried setting IsSelected and Focus on this row as in:

  SharedWindow.ShipmentWin.ShipVM.IsSelected = true;
  bool focused = SharedWindow.ShipmentWin.shipmentDataGrid.Focus();

Am I going about this all wrong and is there some other way to Select the first row in the datagrid and set focus to it? Typically, when a datagrid is created, no row is selected until the user mouse clicks on the desired row.

Any thoughts would be greatly appreciated.

thanks!

like image 962
Bill Campbell Avatar asked Mar 09 '10 14:03

Bill Campbell


2 Answers

Have a look at the FocusManager. It allows you the set the focus to another UI element via the SetFocusedElement method. Additionally, it allows you to determine the currently focused element in your application which is can get handy to debug focus issues. Snoop can be useful, too. It shows the currently focused element in the bottom status bar.

If you use the DataGrid from the WPF Toolkit, be prepared to find some bugs in relation to focus handling. Some have been addressed recently.

like image 88
olli-MSFT Avatar answered Oct 11 '22 13:10

olli-MSFT


It's also worth understanding the difference between logical focus and keyboard focus, which are quite different animals. The .Focus() method sometimes only sets logical focus - which probably isn't what you want.

The documentation for the Focus method tells you that it will return true if the keyboard focus was set, and false otherwise.

like image 20
Dan Puzey Avatar answered Oct 11 '22 13:10

Dan Puzey