WPF 绑定如何区分索引器属性和列表元素?
我有一个以下形式的绑定:
Path=SpecialCollection[0]
SpecialCollection 类扩展了 ObservableCollection 并具有索引器属性。
public T this[string propertyValue]
{
get
{
// do stuff
return default(T);
}
}
我的问题是绑定尝试获取索引器属性值,而不是返回集合中的第 0 个项目。有没有办法强制绑定将 0 视为整数,以便它返回集合元素,而不是调用集合的索引器属性的 getter?
I have a binding of the form:
Path=SpecialCollection[0]
The SpecialCollection class extends ObservableCollection and has an indexer property.
public T this[string propertyValue]
{
get
{
// do stuff
return default(T);
}
}
My problem is that the binding attempts to get the indexer property value, instead of returning the 0th item in the collection. Is there a way to force the binding to treat 0 as an integer so it returns a collection element, instead of invoking the collection's indexer property's getter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 MSDN 你可以告诉绑定作为索引输入的值的类型:
我注意到
Binding
构造函数采用路径字符串 使用另一个PropertyPath
构造函数不是默认的PropertyPath
类型转换器,表示PropertyPath
构造函数确实不是 在这种情况下工作。为了避免此问题,请通过手动设置通过类型转换器调用转换的Path
属性来避免使用Binding
构造函数。According to MSDN you can tell the binding the type of the value entered as index:
I noticed that the
Binding
constructor taking a path string uses anotherPropertyPath
constructor than the defaultPropertyPath
type converter, saidPropertyPath
constructor does not work in this scenario. To avoid the problem avoid theBinding
constructor by setting thePath
property manually which invokes the conversion via type converter.实际上,您有两个索引器属性,一个采用
int
参数,另一个采用string
参数。坦率地说,我不知道绑定表达式在不明确时如何选择使用哪个索引器。如果只有一个,那么它可以将索引强制为索引器参数的类型。如果有两个,它可以抛出异常或根据启发式选择一个。在这种情况下,它显然选择了错误的选择。要解决此问题,您可以将字符串索引器“下一级”移动,使其挂在新属性上,这样它就不会与列表索引器竞争,或者如果您只需要
List[0] 您可以添加一个
First
属性并绕过任一索引器。Actually you have two indexer properties, one that takes an
int
argument and one that takes astring
argument. Frankly, I don't know how the binding expression chooses which indexer to use when it is ambiguous. If there is only one then it can coerce the index to the type of the indexer argument. If there are two, it can either throw an exception or choose one according to a heuristic. In this case, it apparently chose the wrong one.To solve this problem you can either move your string indexer "down a level" so it hangs off of a new property so that it doesn't compete with the list indexer or if all you need is
List[0]
you can add aFirst
property and bypass either indexer.