WPF - 从绑定路径获得一个属性值 [英] WPF - Getting a property value from a binding path
问题描述
如果我有说叫MyObject的一个对象,它有一个名为MyChild属性,它本身有一个名为Name属性。我怎样才能得到Name属性的值,如果我只有一个绑定路径(即MyChild.Name),并为myObject?参考
为MyObject
-我的孩子
-名称
我发现了一个办法做到这一点,但它是相当难看,可能不是非常快...基本上,这个想法是创建一个具有给定路径的结合并把它应用到依赖对象的属性。这样,结合确实检索值的所有工作:
公共静态类PropertyPathHelper
{
公共静态对象的GetValue(obj对象,字符串的PropertyPath)
{
约束力181 =新的Binding(的PropertyPath);
binding.Mode = BindingMode.OneTime;
binding.Source = OBJ;
BindingOperations.SetBinding(_dummy,Dummy.ValueProperty,绑定);
返回_dummy.GetValue(Dummy.ValueProperty);
} 私人静态只读虚拟_dummy =新的虚拟(); 私有类假:DependencyObject的
{
公共静态只读的DependencyProperty ValueProperty =
DependencyProperty.Register(值的typeof(对象)的typeof(虚拟),新UIPropertyMetadata(NULL));
}
}
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屋!