绑定ComboBox

时间:2012-07-10 13:15:53

标签: c# wpf combobox

我做的一切都好吗?

public List<string> combolist { get; set; }

...

this.combolist = new List<string>();
MySqlCommand status_db = new MySqlCommand("select name_ru from request_status", conn);
MySqlDataReader combodata = status_db.ExecuteReader();
   while (combodata.Read())
   {
     combolist.Add(combodata.GetString(0));
   }
   this.DataContext = this;
xaml中的

<ComboBox ItemsSource="{Binding Path=combolist}"... 

但组合框是空的,有什么不对?

2 个答案:

答案 0 :(得分:0)

您应该使用ObservableCollection。在调用InitializeComponent()

之前实例化ObservableCollection

答案 1 :(得分:0)

这有效:

usercontrol1.xaml

<Grid>
    <ComboBox ItemsSource="{Binding Combolist}" />
</Grid>

usercontrol1.xaml.cs

public partial class UserControl1 : UserControl
{
    public ObservableCollection<string> Combolist { get; private set; }

    public UserControl1()
    {
        this.Combolist = new ObservableCollection<string>();//just initialize once!
        InitializeComponent();
        //if you wanna load new data, call .Clear() before
        //this.Combolist.Clear();
        //MySqlCommand status_db = new MySqlCommand("select name_ru from request_status", conn);
        //MySqlDataReader combodata = status_db.ExecuteReader();
        //while (combodata.Read())
        //{
        //    Combolist.Add(combodata.GetString(0));
        //}

        //test
        this.Combolist.Add("qqqq");
        this.Combolist.Add("wwww");
        this.Combolist.Add("eeee");
        this.Combolist.Add("rrrr");

        this.DataContext = this;
    }
}