【发布时间】:2015-04-05 07:12:38
【问题描述】:
我制作了一个自定义的可搜索组合框,在默认的 CollectionView 上定义了一个过滤器
CollectionViewSource.GetDefaultView(this.ItemsSource)
view.Filter += FilterPredicate;
ComboBox 的过滤谓词:
private bool FilterPredicate(object value)
{
return PropertyPathHelper.GetValue(value, FilterPropertyPath).ToString().Contains(PART_FilterTextBox.Text);
}
//value is instance of current filtered item: Student{ FullName="SunnyXyz" , Age=30 }
//& FilterPropertyPath="FullName"
FilterPropertyPath 是一个“字符串”DependancyProperty,其作用类似于 DisplayMemberPath,用于定位在绑定项中应用过滤的文本属性。 PropertyPathHelper.GetValue 创建一个虚拟绑定并解析绑定路径,但是这种方法很慢/不优雅/似乎不是正确的方法。 (来自https://stackoverflow.com/a/7041604/852318)
任何人都可以提供另一种正确的方式或更优雅的方式来传递 FilterPropertyPath 信息
【问题讨论】:
-
我不确定我是否完全理解这个问题,但您可以使用反射从字符串中动态获取属性值。
value.GetType().GetProperty(FilterPropertyPath).GetValue(value)请注意,如果未找到具有给定名称的属性,则 GetProperty 将返回 null。 -
@SzabolcsDézsi,关于这种方法的两个问题,1. 反射非常慢,2. 我需要它来处理嵌套路径?比如 A 类 { B 类 { C 类 { string GetMe { get;放; } } } },然后是 value.GetType().GetProperty("A.B.C.GetMe").GetValue(value)
-
您说得对。没有考虑嵌套路径。