2013-06-20 38 views
0

更新:Discusion显示问题只在您将自定义控件文本框托管在通过winforms应用程序中的elementhost再次托管的wpf应用程序中时才会出现。WPF MessageBox将键盘焦点返回给错误的控件

我有一个从TextBox中进行WPF-CustomControl的Inherting。我重写OnLostKeyBoardFocus方法。

作为此方法的一部分,我提出了一个事件。一个事件处理程序显示一个MessageBox(这不在我的控制之下)。当用户关闭MessageBox时,KeyBoardFocus直接返回到TextBox。尽管OnLostKeyboardFocus(...)仍然没有返回。

自动(重新)专注于我的TextBox控件,对我造成了一系列问题。除了使用Dispatcher.BeginInvoke()分派事件之外,我能否绕过这种行为?

class MyTextBoxCustomControl : TextBox { 

    public event EventHandler<EditCompletedEventArgs> EditCompleted; 

    private void OnEditCompleted(EditCompletedEventArgs e) 
    { 
     var handler = EditCompleted; 
     if (handler != null) handler(this, e); 
    } 

    protected override OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e){ 

     base.OnLostKeyboardFocus(e); 

     OnEditCompleted(new EditCompletedEventArgs()) 

     //Before this point is reached OnGotKeyboardFocus(...) is called 
    } 

    protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) 
    { 
     base.OnGotKeyboardFocus(e); 

     //Is called twice, directly after MessageBox is closed and 
     //after OnLostKeyboardFocus(...) returns 
    } 
} 

class MyEventHandler { 

    private void Test(){ 

     var myTBCC = new MyTextBoxCustomControl(); 

     //Closing the message box will return focus to myTBCC, which directly 
     //causes OnGotKeyboardFocus to be called 
     myTBCC.EditCompleted += (a, b) => 
            MessageBox.Show("PressOk");      
    } 
} 

回答

1

你可以尝试拨打发件人.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); MessageBox.Show之后。

编辑:

... 

MessageBox.Show("PressOk"); 
((MyTextBoxCustomControl)a).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); 

... 
+0

我尝试这样做。在以下情况中导致问题,当文本框处于焦点状态,然后用户在其他窗口中单击时:调用OnLostKeyboard,显示messagebox,用户单击确定,调用MoveFocus;这导致(重新)专注于wpf窗口,从而导致(重新)聚焦我的文本框控件,导致OnGotKeyboardFocus被调用,最后,焦点移动到我的wpf窗口中的下一个元素。 – user1182735

+1

尝试了您的代码,即使没有“MoveFocus”,它也能正常工作。显示离开自定义控件'MessageBox'后,焦点移动到下一个控件。 – majk86

+0

我的问题是OnGotKeyboardFocus在我的文本框自定义控件被调用时,OnLostKeyboardFocus尚未返回。最后的焦点在哪里,对我来说无关紧要。当你的代码已经运行了,你还可以检查一下吗?所以我可以排除这一点。完全不相关导致这种行为。在我的代码中OnGotKeyboardFocus仍然被调用。 – user1182735