Search code examples
c#wpfdatacontext

How to Bind my list to a combobox in WPF


I want to fill combobox content with my list in WPF. I can do it normally in winform but wpf looks a bit different..

I dont create any code in XAML. whole controls create dynamically and at run time..

so here is my code

cmbKriterKategori is a combobox.

                cmbKriterKategori.DisplayMemberPath = "Value";
                cmbKriterKategori.SelectedValuePath = "Key";
                cmbKriterKategori.ItemsSource = yHelper.GetCriterList().ToList();

an error occours

Items collection must be empty before using ItemsSource.

and I also tried like that

                cmbKriterKategori.DisplayMemberPath = "Value";
                cmbKriterKategori.SelectedValuePath = "Key";
                cmbKriterKategori.DataContext = yHelper.GetCriterList().ToList();

it doesnt occour any error but combobox hasnt any item..

yHelper.GetCriterList().ToList(); this function returns List> and yHelper.GetCriterList() returns Dictionary

I used that code in winform and it works..

                cmbKriterKategori.DisplayMember = "Value";
                cmbKriterKategori.ValueMember ="Key";
                cmbKriterKategori.DataSource = yhelper.GetCriterList().ToList();

So, What is the problem?


Solution

  • you have to clear your combo items so the Items collection must be empty before using ItemsSource exception won't be thrown

            cmbKriterKategori.Items.Clear();
            cmbKriterKategori.DisplayMemberPath = "Value";
            cmbKriterKategori.SelectedValuePath = "Key";
            cmbKriterKategori.ItemsSource = yHelper.GetCriterList().ToList();