WPF - 从绑定路径获取属性值
如果我有一个名为 MyObject 的对象,它有一个名为 MyChild 的属性,它本身有一个名为 Name 的属性。如果我只有一个绑定路径(即“MyChild.Name”)和对 MyObject 的引用,如何获取该 Name 属性的值?
MyObject
-MyChild
-Name
if I have an object say called MyObject, which has a property called MyChild, which itself has a property called Name. How can I get the value of that Name property if all I have is a binding path (i.e. "MyChild.Name"), and a reference to MyObject?
MyObject
-MyChild
-Name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我找到了一种方法来做到这一点,但它非常丑陋,而且可能不是很快...基本上,这个想法是创建一个与给定路径的绑定并将其应用于依赖对象的属性。这样,绑定就会完成检索值的所有工作:
I found a way to do this, but it's quite ugly and probably not very fast... Basically, the idea is to create a binding with the given path and apply it to a property of a dependency object. That way, the binding does all the work of retrieving the value:
我开发了一个 nuget 包 Pather.CSharp 正是您所需要的。
它包含一个
Resolver
类,该类具有一个Resolve
方法,其行为类似于 @ThomasLevesque 的GetValue
方法。示例:
它甚至支持通过索引集合访问或通过密钥字典访问。
这些路径的示例是:
I developed a nuget package Pather.CSharp that does exactly what you need.
It contains a class
Resolver
that has aResolve
method which behaves like @ThomasLevesque'sGetValue
method.Example:
It even supports collection access via index or dictionary access via key.
Example paths for these are:
不确定你想做什么,但是以及如何做(xaml 或代码),但你总是可以命名你的对象
,然后在代码
或 xaml 中使用它
not sure what you want to do but and how (xaml or code) yet you can always name your object
an then use it in code
or in xaml
我就是这样做的。如果这是一个糟糕的主意,请告诉我,因为 C# 对我来说只是副业,所以我不是专家 objectToAddTo 的类型为 ItemsControl:
I am doing it this way. Please let me know if this is a terrible idea, as C# is just a side job for me so I am not an expert objectToAddTo is of type ItemsControl: