【问题标题】:Filtering of combobox in c# wpfc# wpf中组合框的过滤
【发布时间】:2020-04-01 17:09:04
【问题描述】:

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”的项目。

【问题讨论】:

    标签: c# wpf combobox filtering


    【解决方案1】:

    您应该将字符串输入绑定到 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2017-09-02
      • 1970-01-01
      • 2010-12-29
      相关资源
      最近更新 更多