2013-03-22 90 views
1

对于编辑组合框使用LostFocus事件时,我遇到了一个问题。在可编辑组合框上使用LostFocus事件时的Messagebox

private void comboBox8_LostFocus(object sender, RoutedEventArgs e) 
    { 
     ... 
      else if (8int <= 7int && 8int >= 100) 
      { 
       MessageBox.Show("Error description", "Error!", MessageBoxButton.OK, MessageBoxImage.Information); 
      } 
      else 
      ... 
    } 

一切正常,除了messagebox显示,即使我用鼠标点击编辑的comboBox文本字段。如果我使用前一个字段的“标签”,则没有消息框。但直接鼠标点击会导致错误的消息框。我需要它仅在使用“tab”离开该组合框或在其他位置单击鼠标(lostfocus)时才会显示。任何人都可以帮我咨询一下吗?我找不到类似的情况。谢谢。

回答

1

您想要倾听ComboBoxLostFocusTextBox部分。

 private void comboBox8_Loaded(object sender, RoutedEventArgs e) 
     { 
      TextBox tb = (TextBox)(sender as ComboBox).Template.FindName("PART_EditableTextBox", (sender as ComboBox)); 
      if (tb != null) 
       tb.LostFocus += new RoutedEventHandler(tb_LostFocus); 
     } 

     void tb_LostFocus(object sender, RoutedEventArgs e) 
     { 
      ... 
      else if (8int <= 7int && 8int >= 100) 
      { 
       MessageBox.Show("Error description", "Error!", MessageBoxButton.OK, MessageBoxImage.Information); 
      } 
      else 
      ... 
     } 
+1

现在当您直接点击下拉箭头时,没有错误的消息框,但是当您直接点击文本时仍然存在错误的消息框。正如我写的组合框是可编辑的。 – Mike 2013-03-22 17:35:23

+0

@Mike看到更新的答案,这应该可以解决它。 – JeremyK 2013-03-22 17:48:09

1

哦,那对我的作品:

private void comboBox8_LostFocus(object sender, RoutedEventArgs e) 
     { 
     ... 
     else if (8int <= 7int && 8int >= 100) 
     { 
      if (!comboBox8.IsKeyboardFocusWithin) 
       { 
        MessageBox.Show("Error description", "Error!", MessageBoxButton.OK, MessageBoxImage.Information); 
       } 
     } 
     else 
     ... 
     } 

谢谢!

+0

你有没有把这个添加到我的答案中,或者这是一个不同的答案? – JeremyK 2013-03-22 17:52:54

+0

这是不同的,但我真的很感谢你的解决方案!谢谢。 – Mike 2013-03-22 17:54:05

+0

您是否将此添加到您失去的焦点活动中?因为当我尝试这个时,当我离开焦点时,我会得到两个消息框。 – JeremyK 2013-03-22 17:54:36