繁体   English   中英

c# wpf 中组合框的过滤

[英]Filtering of combobox in c# wpf

XAML:

<ComboBox x:Name="cmb" HorizontalAlignment="Left" 
              Margin="183,39,0,0" 
              VerticalAlignment="Top" 
              Width="120" 
              ItemsSource="{Binding FilteredNames, Mode=OneWay}"
              IsTextSearchEnabled="True"
              IsEditable="True"
              TextSearch.Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged}"/>

视图模型:

public List<string> FilteredNames
{
    get
    {
        return (names.FindAll(x => x.Contains(filter))).ToList<string>();
    }
}

public string Filter
{
    get
    {
        return this.filter;
    }
    set
    {
        this.filter = value;
        NotifyPropertyChanged("FilteredNames");
    }
}

public ViewModel()
{
    this.names = new List<string>() { "Jerry", "Joey", "Roger", "Raymond", "Jessica", "Mario", 
                                              "Jonathan" };
    this.filter = "";
}

这是我已经实施的。 请帮助我了解如何在组合框中获取过滤下拉列表。 就像当我输入“j”时,我想获取其中包含“j”的所有项目。

您应该将字符串输入绑定到 ComboBox 的 Text 属性:

Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged}"

另外我建议使用CollectionView进行这样的过滤:

public ICollectionView FilteredNames { get; set; }
IList<string> names = new List<string>() { "Jerry", "Joey", "Roger", "Raymond", "Jessica", "Mario", "Jonathan" };

public VM()
{
    FilteredNames = CollectionViewSource.GetDefaultView(names);
    FilteredNames.Filter = (obj) => 
    {
        if (!(obj is string str))
            return false;

        return str.Contains(filter);
    };
}

string filter = "";
public string Filter
{
    get 
    {
        return this.filter;
    }
    set 
    {
        this.filter = value;
        FilteredNames?.Refresh();
    }
}

XAML:

<ComboBox x:Name="cmb" HorizontalAlignment="Left" 
              Margin="183,39,0,0" 
              VerticalAlignment="Top" 
              Width="120" 
              ItemsSource="{Binding FilteredNames, Mode=OneWay}"
              IsTextSearchEnabled="True"
              IsEditable="True"
              TextSearch.Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged}"/>

ViewModel:

public List<string> FilteredNames
{
    get
    {
        return (names.FindAll(x => x.Contains(filter))).ToList<string>();
    }
}

public string Filter
{
    get
    {
        return this.filter;
    }
    set
    {
        this.filter = value;
        NotifyPropertyChanged("FilteredNames");
    }
}

public ViewModel()
{
    this.names = new List<string>() { "Jerry", "Joey", "Roger", "Raymond", "Jessica", "Mario", 
                                              "Jonathan" };
    this.filter = "";
}

这就是我已经实现的。 请帮助我了解如何在组合框中获取过滤下拉列表。 就像我输入“ j”时一样,我想获取其中包含“ j”的所有项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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