2013-03-20 116 views
1

我有一個ComboBox,帶有一些ComboBoxItems。我想用鼠標懸停在ComboBoxItem上時觸發一個事件。這是迄今爲止我嘗試過的代碼,但事件不會觸發 - 即當我放置一個斷點時,事件不會被輸入。事件並沒有被解僱

private void cmbValue_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
     { 
      ComboBox cmb = sender as ComboBox; 
      cmb.Items.Clear(); 

      //Iterates through all virtual tables 
      foreach (TableContainer table in listOpenUnjoinedTables) 
      { 
       ComboBoxItem item = new ComboBoxItem(); 
       item.MouseEnter += item_MouseEnter; 

       if (table.IsVirtual == false) 
       { 
        item.Content = "[" + table.TableDescription + "]"; 
       } 
       else 
       { 
        item.Content = "[" + table.View.Name + "]"; 
       } 

       item.Tag = table; 
       cmb.Items.Add(item); 
      } 
     } 

private void item_MouseEnter(object sender, MouseEventArgs e) 
     { 
      ComboBoxItem item = sender as ComboBoxItem; 

      //Do task 
     } 
+1

如何將事件處理程序分配給ComboBox? – DHN 2013-03-20 13:35:00

+0

@DHN它被分配到ComboBoxItem - 'item.MouseEnter + = item_MouseEnter;' – WPF 2013-03-20 13:36:03

+0

他做了'item.MouseEnter + = item_MouseEnter;' – 2013-03-20 13:36:37

回答

0

嘗試GotFocus活動。即使用戶使用鍵盤選擇項目,也會觸發。我相信那是你確實想在這裏:)

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     var comboBoxItem1 = new ComboBoxItem(); 
     var comboBoxItem2 = new ComboBoxItem(); 

     comboBoxItem1.Content = new Button() { Content = "button1" }; 
     comboBoxItem1.GotFocus += (sender, args) => lbl1.Content = "1111"; 
     comboBoxItem2.Content = "222222"; 
     comboBoxItem2.GotFocus += (sender, args) => lbl1.Content = "2222"; 

     comboBox1.Items.Add(comboBoxItem1); 
     comboBox1.Items.Add(comboBoxItem2); 
    } 
} 

enter image description here

enter image description here

+0

那麼如果你把鼠標懸停在一個'Control'上,它就不會獲得焦點。所以我不明白,這應該如何工作。如果我錯了,請糾正我。 – DHN 2013-03-20 13:47:59

+0

也沒有運氣。 – WPF 2013-03-20 13:51:03

+0

可能是我不明白這裏的問題。如果是這樣,請原諒。它雖然爲我工作。 – 2013-03-20 13:56:33

0

你不小心刪除designer.cs事件?

+0

我不認爲這是 - 我創建了一個新的項目,問題是在那裏太。 – WPF 2013-03-20 15:47:58