Reputation: 452
I am facing a problem though it might have a simple solution but was not able to find it out.
I have a page (say mainPage) with several buttons inside that on which I enable "Enter" key-press for one button (say Submit) by setting the IsDefault="true" in xaml for that button and it worked fine.
Clicking on the other buttons on my mainPage will open a popup which contain 2 buttons "Yes" and "No". setting IsDefault="true" property for "Yes" will not work when I press enter. (for information it will not work for the Submit button as well and that is also not a problem and I think I have a solution for that as well )
how should I enable this feature for the buttons in popup?
(for more info we have a button which create a popup that have button and textbox inside that.in that case setting IsEnable="true" for button inside the popup will do the job for the button but only if we click on the textbox. I tried setting focus on the textbox after observing this behavior so it might help but setting focus on the textbox does not work. use to set focus on textbox like this: Focusable="True" FocusManager.FocusedElement="{Binding ElementName=textboxName}" )
Upvotes: 4
Views: 8341
Reputation: 132568
You need to set focus on your Popup
first so it can respond to the Enter
key
There are two types of Focus in WPF: Keyboard and Logical. You can have multiple objects with Logical focus providing they're in different Focus Scopes (for example, you can have one element focused in your Window, and another in your Popup), but only one object can have Keyboard focus.
To set focus in a Popup, I usually just use the Loaded
event which executes anytime the Popup becomes visible and loads.
MyTextBox.Focus(); // Set Logical Focus
Keyboard.Focus(MyTextBox); // Set Keyboard Focus
Edit
Sometimes if something else in your application is stealing focus right after the Loaded
event, you can use the Dispatcher
to run your Focus code at a later DispatcherPriority, such as Input
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(delegate() {
MyTextBox.Focus(); // Set Logical Focus
Keyboard.Focus(MyTextBox); // Set Keyboard Focus
}));
Upvotes: 3