【问题标题】:Filtering a bound listbox c#过滤绑定的列表框c#
【发布时间】:2020-12-01 05:26:17
【问题描述】:

我有一个 XAML 文件,其中包含一个列表框和一个文本框。

列表框充满了数据绑定,如下所示:

<ListBox x:Name="lstboxNotes"
         ItemsSource="{Binding Notes}"
         SelectedItem="{Binding SelectedNote}"
        Grid.Row="1"
         ></ListBox>

我拥有的文本框应该在您输入时实时过滤掉结果。 例如,您在列表框中有 5 个注释,如果您搜索“注释 2”,则只会显示该注释,或者名称中包含“注释 2”的任何其他注释。

我知道您可以使用 datatable/dataview 轻松完成此操作,但我不知道如何将我的 Itemssource 设置为数据表。

【问题讨论】:

    标签: c# xaml data-binding listbox


    【解决方案1】:

    我只是通过拥有 3 个属性来进行过滤:

    1. 搜索文本
    2. 主要收藏
    3. 过滤的 IEnumerable

    注意,我在示例中使用https://github.com/Fody/PropertyChanged 来实现更简单的INotifyPropertyChanged ([AlsoNotifyFor("FilteredItems")])。您可以通过手动实现INotifyPropertyChanged 来在没有此库的情况下实现相同目的。

    首先我将 TextBox 绑定到字符串属性:

    [AlsoNotifyFor("FilteredItems")]
     public string ItemsSearch { get; set; } = string.Empty;
    

    并像这样绑定它。

    (请注意UpdateSourceTrigger=PropertyChanged,因此每次按下按钮时绑定都会更新。)

    Text="{Binding InventorySearch, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=UserControl_Main}"
    

    然后是我存储所有对象的主集合:

    (如果您打算在运行时添加和删除对象,您可以使用 ObservableColletion,以更方便地更新 UI)

    [AlsoNotifyFor("FilteredItems")]
     public List<string> Items { get; set; } = new List<string>();
    

    最后过滤了 Enumerable:

     public IOrderedEnumerable<string> FilteredItems => 
          Items.Where(x => x.ToUpper().Contains(ItemsSearch.ToUpper()))
    

    【讨论】:

    • 谢谢,我花了一点时间弄清楚如何在我的用例中实现这一点,但最终我们做到了!
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多