无法将键盘焦点设置为TextBox

时间:2019-06-04 21:57:26

标签: c# textbox focus

我正在使用System.Windows.Controls命名空间来创建带有许多MenuItems的ContextMenu。其中一个MenuItem包含一个TextBox作为其标题,单击该标题时,应将其赋予键盘焦点,以便用户可以在其中键入以指定配置设置。它可以成功检测到鼠标单击,但是令我感到困惑的是我无法将键盘焦点设置在它上面。不幸的是,我尝试了所有在网上看到的内容,但收效甚微。

下面的代码显示了我尝试使它成为键盘焦点的不同方法。我只能使用其中一个功能来获得逻辑上的焦点,但是没有什么可以正确设置键盘焦点。我还尝试了在TextBox的父项defineItem上使用所有这些功能,但是没有什么不同。

//*Upon catching a mouse click event:*

MenuItem specifyItem = //MenuItem sent by the event;
TextBox specifyBox = //specifyItem's header;

bool hasLogicalFocus; //store results of attempting logical focus
bool hasKeyboardFocus; //store results of attempting keyboard focus

//attempt UIElement.Focus(); fails both
specifyBox.Focus();
hasLogicalFocus = specifyBox.IsFocused; //false
hasKeyboardFocus = specifyBox.IsKeyboardFocused; //false

//attempt Keyboard.Focus(specifyBox); fails both
Keyboard.ClearFocus(); // <-- did not make a difference
Keyboard.Focus(specifyBox);
hasLogicalFocus = specifyBox.IsFocused; //false
hasKeyboardFocus = specifyBox.IsKeyboardFocused; //false

//attempting asynchronous with dispatcher; fails both
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
{
    specifyBox.Focus();         // Set Logical Focus
    Keyboard.Focus(specifyBox); // Set Keyboard Focus
}));
hasLogicalFocus = specifyBox.IsFocused; //false
hasKeyboardFocus = specifyBox.IsKeyboardFocused; //false

/*This actually does set logical focus, but this isn't 
 * helpful because I need keyboard focus
 */
FocusManager.SetFocusedElement(specifyItem, specifyBox);
hasLogicalFocus = specifyBox.IsFocused; //true!
//still doesn't have keyboard focus

我希望将defineBox的键盘焦点设置为true,以便用户可以在其中键入内容,但是在执行这些操作后,boolean defineBox.IsKeyboardFocused始终为false,并且不会捕获键盘上的任何键。

0 个答案:

没有答案