2010-09-08 74 views
1

我有一些簡單的示例WinForms代碼,我嘗試將其轉換爲WPF。這個想法是,如果某個項目被選中,則更改組合框中的項目,如果發生這種情況,則再次下拉組合框。在的WinForms代碼:WPF中的WinForms ComboBox.DroppedDown的等價示例

if (list.Text.Equals("C>>")) 
     { 
      comboBox1.Items.Clear(); 

      comboBox1.Items.Add("<<"); 
      comboBox1.Items.Add("C1"); 
      comboBox1.Items.Add("C2"); 
      comboBox1.Items.Add("C3"); 
      comboBox1.Items.Add("C4"); 
      comboBox1.Items.Add("C5"); 
      comboBox1.Items.Add("C6"); 
      comboBox1.DroppedDown = true; 
     } 

雖然我雖然,這將是一個相當簡單的改變,使用

private void hotListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     if (hotListBox.SelectedItem != null) 
     { 
      if (hotListBox.SelectedItem.Equals("b >>")) 
      { 
       hotListBox.ItemsSource = secondList; 
       hotListBox.IsDropDownOpen = true; 
      } 
      else if (hotListBox.SelectedItem.Equals("<<")) 
      { 
       hotListBox.ItemsSource = initialList; 
       hotListBox.IsDropDownOpen = true; 

      } 
      else if (hotListBox.SelectedItem.Equals("d >>")) 
      { 
       hotListBox.ItemsSource = thirdList; 
       hotListBox.IsDropDownOpen = true; 

      } 
     } 
    } 
在WPF

似乎並沒有以相同的方式工作。我想知道如果有人知道如何做到這一點?

正如在註釋中指出的那樣,我應該說ComboBox中的項目按預期更新,但它不會再次在WPF代碼中下拉。

乾杯,

編輯:更新的代碼

+0

更多關於什麼不工作的信息?組合框中是否顯示新項目?之後不打開嗎? – Bubblewrap 2010-09-08 14:29:32

+0

新項目在ComboBox中可見,它不會隨後打開,而是使用WPF代碼打開,而使用WinForms代碼打開。 – 2010-09-08 14:35:53

回答

3

更改此:

hotListBox.IsDropDownOpen = true; 

對此:

Application.Current.Dispatcher.BeginInvoke(new Action(delegate 
{ 
    hotListBox.IsDropDownOpen = true; 
})); 
+0

工作,謝謝 - 我希望我確切地知道爲什麼(對C#和WPF一般來說很新穎),我覺得這是我去的書! – 2010-09-08 15:43:16

0

它可能更容易只是改變組合框時,列表選擇更改的的ItemSource。

因此,創建一個幾列

List<string> list1 = new List<string>() { "<<", "C1", "C2", "C3", "C4", "C5", "C6" }; 
    List<string> list2 = new List<string>() { "<<", "f", "g", "h", "i" }; 

,然後只是改變列表中選擇改變組合框項目源(使用任何你需要的邏輯)

private void _lbTest_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (_lbTest.SelectedIndex == 0) 
     _comboTest.ItemsSource = list1; 
    else 
     _comboTest.ItemsSource = list2; 

    _comboTest.IsDropDownOpen = true; 
} 
+0

雖然這使得代碼更加整潔(這很好),但它似乎並沒有解決問題,當設置.IsDropDownOpen時,組合框的問題不會消失。( – 2010-09-08 14:54:08

+0

)然後,您需要發佈更多的代碼,因爲它會打開很好,我使用該代碼 – mdm20 2010-09-08 15:16:40

+0

更新後的代碼在我原來的帖子 – 2010-09-08 15:28:15