开发者

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开发者_Go百科, 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜