winforms 可搜寻的缩排下拉式清单

qvsjd97n  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(122)

我想创建一个下拉菜单,可以搜索并以缩进方式显示其选项。我已经创建了一个下拉菜单,它将根据我输入的搜索查询异步刷新。但是,它不允许我显示父匹配的所有子项。
例如:

基本上,当我开始搜索某个东西时,我不仅希望父项出现,而且希望匹配选项的子项也出现。搜索也应该对子项起作用。因此,在美国的情况下,只有奥斯汀出现。
我试图寻找其他解决方案,但我只找到了按顺序添加时缩进某些列表项的选项。尽管如此,搜索仍会正常运行。

iezvtpos

iezvtpos1#

看一下这个Fiddle,并对其进行修改以使用一个名为TextChangedTextBox事件。
提琴码:

public class Country
{
    public string Name { get; set; }
    public List<City> Cities { get; set; }
}

public class City
{
    public string Name { get; set; }
}

public static void Main()
{
    var items = new List<Country>()
    {
        new Country() { Name = "Austria", Cities = new List<City>() { new City() { Name = "Vienna" }, new City() { Name = "Linz" } } },
        new Country() { Name = "Australia", Cities = new List<City>() { new City() { Name = "Sydney" }, new City() { Name = "Melbourne" } } },
        new Country() { Name = "USA", Cities = new List<City>() { new City() { Name = "Austin" }, new City() { Name = "New York" } } }
    };
    var searchTerm = "aus";
    
    var filteredItems = items.Where(i => i.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                                         i.Cities.Any(c => c.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)))
                            .Select(i => new Country()
                                    {
                                        Name = i.Name,
                                        Cities = i.Cities.Where(c => c.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                                                                     i.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList()
                                    })
                            .ToList();
    
    
    Console.WriteLine("****Unfiltered:");
    Output(items);
    Console.WriteLine("\r\n****Filtered:");
    Output(filteredItems);
}

public static void Output(List<Country> countries)
{
    foreach (var country in countries)
    {
        Console.WriteLine(country.Name);
        foreach (var city in country.Cities)
        {
            Console.WriteLine("    " + city.Name);
        }
    }
}

输出量:

****Unfiltered:
Austria
    Vienna
    Linz
Australia
    Sydney
    Melbourne
USA
    Austin
    New York

****Filtered:
Austria
    Vienna
    Linz
Australia
    Sydney
    Melbourne
USA
    Austin

相关问题