简体   繁体   中英

How to change comboBox Item Source when this comboBoxSelectionChanged property is called WPF C#

So I am using external API which is providing class called CatInfoType which have for example int number catid and string catname.

I have a combobox with properties

< ComboBox x:Name="listOfCategories_comboBox" ... SelectionChanged="listOfCategories_comboBox_SelectionChanged"  DisplayMemberPath="catname" />

Then in MainWindow cs file I have:

1) list of this class

    List<CatInfoType> displayedCategories_List = new List<CatInfoType>();

2) in constructor

        var comboBox = listOfCategories_comboBox as ComboBox;
        comboBox.ItemsSource = displayedCategories_List;

3) after some button is clicked then I am filling values of combobox:

            foreach (var item in allCategories_list)
            {
                if (item.catparent == 0)
                {
                    displayedCategories_List.Add(item);
                }
            }

Until now everything is fine, but I would like to change combobox items after same comboBoxSelectionChanged is called:

    private void listOfCategories_comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        CatInfoType selectedCategory = listOfCategories_comboBox.SelectedItem as CatInfoType;
        int selectedCategoryId = selectedCategory.catid;
        int selectedCategoryParentId = selectedCategory.catparent;

        displayedCategories_List.Clear();
        foreach (var item in allCategories_list)
        {
            if (item.catparent == selectedCategoryId)
                displayedCategories_List.Add(item);
        }

        var comboBox = listOfCategories_comboBox as ComboBox; // I think those two lines are useless
        comboBox.ItemsSource = displayedCategories_List;
    }

However the combobox items are not getting changed. I was trying to do it in few ways. None of them get the result.

How I may do this ? Change comboBox Items "on live". After one of those item is pressed I want to clear the list and add new items to be displayed.

I hope code above and description is showing what I would like to do. In case you have questions feel free to ask.

尝试使用ObservableCollection<CatInfoType>代替List<CatInfoType>

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