WPF通过可观察的集合保留搜索中的选中项目

时间:2018-08-16 10:35:51

标签: c# wpf

大家好,我有一个带复选框和文本框的组合框来搜索结果,我要做的是当用户搜索应匹配的特定记录并显示正常时。当用户选中该复选框并尝试再次搜索时,我想保留之前与新搜索一起选中的项目

enter image description here

enter image description here

enter image description here

我的代码在这里

https://drive.google.com/open?id=0ByVjmdncQgagX28zbkRWMVhPdVg3Q3EyYVVOcjkxcE0xWlNJ

与此相关的帖子在这里相同的代码 WPF ComboBox with checkboxes and textbox with search field

1 个答案:

答案 0 :(得分:0)

您需要更新方法multiCombo_TextChange并按以下方式处理选定和搜索的项目作为您的新数据源:

private void multiCombo_TextChange(object sender, EventArgs e)
    {
        TextBox textBox = sender as TextBox;
        Dictionary<string, int> searchedItem = new Dictionary<string, int>(); 
        searchedItem = (GetFacility(data, textBox.Text));
        Dictionary<string, int> selectedItems = new Dictionary<string, int>();
        Dictionary<string, int> allItems = new Dictionary<string, int>();
        foreach (var item in searchedItem)
        {
            allItems.Add(item.Key, item.Value);
        }
        //multiCombo.SelectedItems.Clear();
        foreach (var selectedItem in multiCombo.SelectedItems)
        {

            selectedItems.Add(selectedItem.Key, selectedItem.Value);
        }


        foreach (var select in selectedItems)
        {
            if (!allItems.ContainsKey(select.Key))
            {
                allItems.Add(select.Key, select.Value);
            }
        }
        multiCombo.ItemsSource = allItems;
        foreach (var selected in selectedItems)
        {
            if (!multiCombo.SelectedItems.ContainsKey(selected.Key))
            {
                multiCombo.SelectedItems.Add(selected.Key, selected.Value);
            }

        }

    }