如果我有一个名为MyObject的对象,则该对象具有名为MyChild的属性,其本身具有名为Name的属性。如果我只有绑定路径(即“ MyChild.Name”)和对MyObject的引用,如何获取该Name属性的值?
MyObject
-MyChild
-Name
最佳答案
我找到了一种方法来执行此操作,但是它很丑陋,而且可能不是很快......基本上,该想法是使用给定路径创建绑定并将其应用于依赖对象的属性。这样,绑定就完成了检索值的所有工作:
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 - WPF-从绑定(bind)路径获取属性值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3577802/