In Forms, I can simple use ActiveControl.name to get the name of the active control. However in WPF this doesn't work. What is the WPF command equivalent to Activecontrol.name? I'll take C# or VB, either way. Thank you!
A:
There are a couple of possibilities though I'm not sure either is an exact match for ActiveControl:
- Keyboard.FocusedElement: this static member tells you which element has the keyboard focus in the current application
- FocusManager.GetFocusedElement(): this allows you to get the focused element within a given focus scope. Note that this cannot be used on arbitrary controls, only on controls which are focus scopes (i.e. have FocusManager.IsFocusScope set to true).
Do either of these sound like what you want?
itowlson
2010-01-29 03:43:57
Yes I am looking for whatever has the keyboard focus. So I guess Keyboard.FocusedElement is what I am looking for. I've tried to use it, but I can't seem to get it to work like in console.write(keyboard.focusedelement.name). What am I doing wrong? Thank you!
Buffy Jones
2010-01-29 04:07:16
Are you getting an error? Or nothing happening? What is Keyboard.FocusedElement (try writing its GetType().Name instead)? Does the element have a Name or x:Name set? (Unlike Windows Forms, the WPF designer doesn't give elements names by default.)
itowlson
2010-01-29 19:24:33
The elements (all textboxes) have x:Names. I am trying to determine the name of the textbox has the keyboard focus (like what ActiveControl.Name does for forms). I have tried Console.Write(Keyboard.FocusedElement.GetType().Name) and I get "Object reference not set to an instance of an object" which I assume should be "Window1" (the x:Name of the Window). Thank you for your help.
Buffy Jones
2010-01-30 04:54:49
Maybe I should let you know what I am trying to accomplish as I may be looking at this the wrong way. I have 10 textboxes with x:Names "Description1" through "Description10". I have one visible Textblock with an x:Name of "CurrentBox" that tells me which textbox I am in such as "Description5". What I am currently forced to do is set the GotGocus codebehind of EVERY textbox with something like CurrentBox.Text="Description5". When I add more controls and features to my app, this is going to be a nightmare! Is there a way to bind the textblock "CurrentBox" with the name of current textbox?
Buffy Jones
2010-01-30 05:25:39
After much digging and experimenting, I found what I am looking for as a replacement to ActiveControl.Name.Dim textbox As Object = TryCast(FocusManager.GetFocusedElement(Me), Object)CurrentBox = textbox.NameNow all I need to do is have the window ("Window1") run this code everytime the focus changes. Thank you so much!
Buffy Jones
2010-01-30 06:50:33