0

更新:讨论表明,当您将自定义控件文本框托管在 wpf 应用程序中时,该问题才出现,该应用程序再次通过 winforms 应用程序中的 elementhost 托管。

我有一个从 TextBox 继承的 WPF-CustomControl。我重写了 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");                    
    }
}
4

1 回答 1

1

.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));您可以在 MessageBox.Show 之后尝试调用发件人。

编辑:

...

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

...
于 2013-06-20T13:39:13.143 回答