简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM