2013-03-22 91 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