2016-05-17 73 views
0

我要填充與用戶輸入在同一個WPF窗口中創建一個列表的組合框創建的列表 ,但它不工作 C#填充組合框與用戶開關輸入在同一個WPF窗口

主窗口.xaml.cs

//Here I populate the ComboBox with the List 

private void Window_Initialized_1(object sender, EventArgs e){ 


     List<string> listaCiudad = EstudioService.obtenerCiudad(); 

     this.ciudadesCBx.Items.Clear(); 

     foreach (String ciudad in listaCiudad){ 
      this.ciudadesCBx.Items.Add(ciudad); 
     } 
    } 

    //Here I get the user input from a textBox called ciudadTxt 
    //by clicking in the button named agregarCiudadBtn 

    private void agregarCiudadBtn_Click(object sender, RoutedEventArgs e) 
    { 
     EstudioService.agregarCiudad(ciudadTxt.Text); 

    } 

公共類EstudioService

private static List<String> listaCiudad = new List<string>(); 


    public static void agregarCiudad(String ciudad) 
    { 
     listaCiudad.Add(ciudad); 

    } 

    public static List<String> obtenerCiudad() 
    { 
     return listaCiudad; 
    } 
+0

如果測試把'this.ciudadesCBx.Items.Add(ciudadTxt.Text)''裏面的方法agregarCiudadBtn_Click',將其填充組合框? – Sam

回答

1

使用ObservableCollection<T>代替List<T>。將該可觀察列表放在模型中並將其綁定到組合框。它是空的並不重要。稍後,當您進行輸入時,只需在可觀察列表集合中添加新輸入,並且組合框應立即選取它。

0

問題是,代碼添加List值組合框在Window_Initialized_1 eevent,我相信這個事件觸發(你的情況),只有當形式進行初始化(糾正我,如果事實並非如此)。

將邏輯移至agregarCiudad方法。

this.ciudadesCBx.Items.Clear(); 

oreach (String ciudad in listaCiudad){ 
    this.ciudadesCBx.Items.Add(ciudad); 
} 

所以你的方法應該看起來像

public static void agregarCiudad(String ciudad) 
{ 
    this.ciudadesCBx.Items.Clear(); 
    listaCiudad.Add(ciudad); 
    ciudadesCBx.Items.AddRange(listaCiudad); 

}