views:

324

answers:

4

I'm going to focus hell right now in my WPF application. Focus is jumping around between elements, and seemingly disappearing only to come up on another element when the tab key is repeatedly pressed.

Is there a property I can bind a label on to or something that will simply just tell me what the heck the keyboard focus is latched on to at the time? Sometimes I can see the ant trail (dotted line) indicating something has focus, but I can't tell what it is surrounding to turn the keyboard focus off!

A: 

Focus problems can be very hard to analyze, since almost everything you do with a debugger affects focus.

  • A copy of spy++ that comes with Visual Studio will show you the events going to various controls; this might help.
  • You could log the focus and loss-of-focus events to another place (like a list control in another window). Or even set the current window title to the name of the current object with focus. Then you could get an indication of what currently has focus.

A better question to ask is why is focus jumping around? Are you explicitly setting focus? Maybe a little hint about your implementation (i.e. which container(s) you are using) might help us answer.

lavinio
It's a WPF DataGrid from the WPF Toolkit CTP. For some reason when I delete an item from the collection the DataGrid is bound to, the focus jumps from inside the grid, to something outside the grid. The ant trail shows up around the entire grid.
Jippers
A: 

What you are likely looking for is:

(System.Windows.Input.Keyboard.FocusedElement as FrameworkElement).Name

You will have to setup a DependencyProperty for it so that you can bind to it though.

Vaccano

Vaccano
how would I do that? i'm trying to follow the example from MSDN here but not having much luck. http://msdn.microsoft.com/en-us/library/system.windows.dependencyobject.aspx
Jippers
A: 

Maybe you could try setting proper values to the TabIndex property of the controls? This should make the focus "jump" over the "path" you want it to jump when pressing Tab.

arconaut
A: 

I can highly recommend reading this article. It comes with some source code that can help debug focus issues, I often end up using this code to help with my own focus issues.

http://www.julmar.com/blog/mark/PermaLink,guid,2974164f-97c1-4e20-85f9-416cf6bed219.aspx

Ashley Davis