views:

383

answers:

2

Hi,

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!

A: 

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.

olli
Thanks Olli! I'll take a look at this right now.
Bill Campbell
This was what I was looking for, but it wasn't simple to figure out even though you pointed me in the right direction. I needed to put code in the onload method to set the focus like: Keyboard.Focus(shipmentDataGrid);where the shipmentDataGrid is the owner of my keyboard shortcut keys.
Bill Campbell
A: 

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.

Dan Puzey
Thanks Dan! You are indeed correct and this was something that I hadn't realized. It is the keyboard focus that I needed to set.
Bill Campbell