C#填充组合框与用户开关输入在同一个WPF窗口

问题描述:

我要填充与用户输入在同一个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

使用ObservableCollection<T>代替List<T>。将该可观察列表放在模型中并将其绑定到组合框。它是空的并不重要。稍后,当您进行输入时,只需在可观察列表集合中添加新输入,并且组合框应立即选取它。

问题是,代码添加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); 

}