过滤绑定列表框 c#
Filtering a bound listbox c#
我有一个 XAML 文件,其中包含一个列表框和一个文本框。
列表框填充了数据绑定,如下所示:
<ListBox x:Name="lstboxNotes"
ItemsSource="{Binding Notes}"
SelectedItem="{Binding SelectedNote}"
Grid.Row="1"
></ListBox>
我的文本框应该在您输入时实时过滤出结果。
例如,您在列表框中有 5 个注释,如果您搜索 'note 2',则只会显示该注释,或者任何其他名称中包含 'note 2' 的注释。
我知道你可以用 datatable/dataview 很容易地做到这一点,但我不知道如何将我的 Itemssource 设置为数据表。
我只是通过具有 3 个属性来进行过滤:
- 搜索文本
- 主要合集
- 过滤 IEnumerable
请注意,我在示例 ([AlsoNotifyFor("FilteredItems")]
) 中使用 https://github.com/Fody/PropertyChanged 来实现更简单的 INotifyPropertyChanged
实现。您可以通过手动实现 INotifyPropertyChanged
.
在没有此库的情况下实现相同的效果
首先我将 TextBox 绑定到字符串 属性:
[AlsoNotifyFor("FilteredItems")]
public string ItemsSearch { get; set; } = string.Empty;
然后这样绑定。
(请注意 UpdateSourceTrigger=PropertyChanged
,因此绑定会随着每次按下按钮而更新。)
Text="{Binding InventorySearch, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=UserControl_Main}"
然后是我存储所有对象的主集合:
(如果打算在运行时增删对象,可以使用ObservableCollection,更新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()))
我有一个 XAML 文件,其中包含一个列表框和一个文本框。
列表框填充了数据绑定,如下所示:
<ListBox x:Name="lstboxNotes"
ItemsSource="{Binding Notes}"
SelectedItem="{Binding SelectedNote}"
Grid.Row="1"
></ListBox>
我的文本框应该在您输入时实时过滤出结果。 例如,您在列表框中有 5 个注释,如果您搜索 'note 2',则只会显示该注释,或者任何其他名称中包含 'note 2' 的注释。
我知道你可以用 datatable/dataview 很容易地做到这一点,但我不知道如何将我的 Itemssource 设置为数据表。
我只是通过具有 3 个属性来进行过滤:
- 搜索文本
- 主要合集
- 过滤 IEnumerable
请注意,我在示例 ([AlsoNotifyFor("FilteredItems")]
) 中使用 https://github.com/Fody/PropertyChanged 来实现更简单的 INotifyPropertyChanged
实现。您可以通过手动实现 INotifyPropertyChanged
.
首先我将 TextBox 绑定到字符串 属性:
[AlsoNotifyFor("FilteredItems")]
public string ItemsSearch { get; set; } = string.Empty;
然后这样绑定。
(请注意 UpdateSourceTrigger=PropertyChanged
,因此绑定会随着每次按下按钮而更新。)
Text="{Binding InventorySearch, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=UserControl_Main}"
然后是我存储所有对象的主集合:
(如果打算在运行时增删对象,可以使用ObservableCollection,更新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()))