问题描述
列表框充满了数据绑定,如下所示:
<ListBox x:Name="lstBoxNotes"
ItemsSource="{Binding Notes}"
SelectedItem="{Binding Selectednote}"
Grid.Row="1"
></ListBox>
我输入的文本框应该实时过滤出结果。 因此,例如,您在列表框中有5个注释,如果您搜索“注释2”,则只会显示该注释,或者其他任何名称中包含“注释2”的注释。
我知道您可以使用datatable / dataview很容易地做到这一点,但是我不知道如何将ItemsSource设置为datatable。
解决方法
我只是通过具有3个属性来进行过滤:
- SearchText
- 主要收藏
- 已过滤的IEnumerable
请注意,因此我在示例(replace()
)中使用https://github.com/Fody/PropertyChanged来实现更简单的SpannableStringBuilder
。如果没有此库,则可以通过手动实现INotifyPropertyChanged
来实现相同的目的。
我首先将TextBox绑定到字符串属性:
[AlsoNotifyFor("FilteredItems")]
并像这样绑定它。
(请注意INotifyPropertyChanged
,因此每按一次按钮,绑定就会更新。)
[AlsoNotifyFor("FilteredItems")]
public string ItemsSearch { get; set; } = string.Empty;
然后在主集合中存储所有对象:
(如果计划在运行时添加和删除对象,可以更方便地更新UI,则可以使用ObservableColletion)
UpdateSourceTrigger=PropertyChanged
最后过滤了Enumerable:
Text="{Binding InventorySearch,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=UserControl_Main}"