【问题标题】:How can I return focus to a control in WPF from within the lost focus event of the same control?如何从同一控件的失去焦点事件中将焦点返回到 WPF 中的控件?
【发布时间】:2015-05-30 02:24:22
【问题描述】:

在我的WPF 应用程序中,我在textbox 控件的lostfocus 事件中进行了一些输入验证。如果文本不符合正确的标准,我会清除 textbox 中的文本。这很好用。我遇到的麻烦是在查看消息框后将焦点返回到控件。例如当我使用下面的代码时,文本框焦点方法在我关闭消息框后重新触发失去焦点事件。

 private void TaskNameBox_LostFocus(object sender, RoutedEventArgs e)

{

    ... validation logic here

    MessageBox.Show("Message.", "Error", MessageBoxButton.OK);            
    TaskNameBox.Focus();
 }

我不知道为什么 Focus 方法会重新触发丢失的焦点事件,但我需要一种方法来在失去焦点后将焦点重新放在 TaskNameBox 控件上。任何建议将不胜感激。我是WPF 的新手。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    如下使用:

    private void TaskNameBox_LostFocus(object sender, RoutedEventArgs e)
    
    {
    
        ... validation logic here
    
        MessageBox.Show("Message.", "Error", MessageBoxButton.OK); 
    
        Dispatcher.BeginInvoke((ThreadStart)delegate
                {
                    TaskNameBox.Focus();
                });
     }
    

    【讨论】:

      【解决方案2】:

      试试这个 FocusManager.SetFocusedElement

      https://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.setfocusedelement(v=vs.110).aspx

      FocusManager.SetFocusedElement(parentElement, txtCompanyID)
      

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 2014-06-30
        • 2010-10-02
        • 2023-03-19
        • 1970-01-01
        相关资源
        最近更新 更多