【发布时间】:2020-05-19 17:55:11
【问题描述】:
我有一个绑定到SearchText 的TextBox,它过滤了GridView。我正在使用 MVVMLight 和 Fody.PropertyChanged。
下面的代码有效。但是,我觉得我应该能够在构造函数中将ExamsGridView.Filter 指向我的谓词,将SearchText 保留为自动属性({ get; set; }),并从@ 的“实时”值中读取谓词987654330@ 每次。
我已经用SearchPredicate(一个函数)和Pred(一个谓词对象)尝试了它,显然这些尝试已经注释了SearchText setter的最后一行并且取消了构造函数的最后一行.
现在,当我写完所有内容时,我确实意识到,如果没有来自 setter 的调用,实际上并没有任何“每次”的概念。
仍然觉得也许以某种方式是可能的。
有没有一种方法可以根据我绑定的字符串属性进行过滤,而无需在每次文本更改时主动重置过滤器/谓词?
public class ExamsIndexViewModel : ViewModelWithExam
{
private string searchText;
public ObservableCollection<Exam> ExamsList { get; }
public ICollectionView ExamsGridView { get; private set; }
public string SearchText
{
get => searchText;
set
{
searchText = value;
ExamsGridView.Filter = SearchPredicate;
}
}
public ExamsIndexViewModel()
{
// get the exams to display
ExamsList = CoreMediator.GetExamsForPatient();
ExamsGridView = CollectionViewSource.GetDefaultView(ExamsList);
// ExamsGridView.Filter = Pred;
}
private Predicate<object> Pred => exam => string.IsNullOrEmpty(searchText) || ((Exam)exam).Name.IndexOf(SearchText, StringComparison.CurrentCultureIgnoreCase) != -1;
private bool SearchPredicate(object exam)
{
return string.IsNullOrEmpty(searchText) || ((Exam)exam).Name.IndexOf(SearchText, StringComparison.CurrentCultureIgnoreCase) != -1;
}
}
(xaml 样本)
<TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"/>
<DataGrid ItemsSource="{Binding ExamsGridView}"
...
...
【问题讨论】:
-
如果你在构造函数中设置
ExamsGridView.Filter += SearchPredicate;,那不是你想要的吗?如果不是,请解释会发生什么。 -
不,当我尝试这样做(并从
SearchTextsetter 中删除该行)时,没有任何反应。