WPF - 从绑定路径获取属性值 [英] WPF - Getting a property value from a binding path
问题描述
如果我有一个名为 MyObject 的对象,它有一个名为 MyChild 的属性,它本身有一个名为 Name 的属性.如果我只有一个绑定路径(即MyChild.Name")和对 MyObject 的引用,我如何获得该 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
推荐答案
我找到了一种方法来做到这一点,但它很丑陋而且可能不是很快......基本上,这个想法是创建一个与给定路径的绑定并将其应用于依赖对象的属性.这样,绑定就完成了检索值的所有工作:
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:
public static class PropertyPathHelper
{
public static object GetValue(object obj, string propertyPath)
{
Binding binding = new Binding(propertyPath);
binding.Mode = BindingMode.OneTime;
binding.Source = obj;
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
return _dummy.GetValue(Dummy.ValueProperty);
}
private static readonly Dummy _dummy = new Dummy();
private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
}
}
这篇关于WPF - 从绑定路径获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!