WPF - 从绑定路径获取属性值

WPF - 从绑定路径获取属性值

问题描述:

如果我有一个名为MyObject的对象,该对象具有名为MyChild的属性,该属性本身具有名为Name的属性。如果我拥有的是一个绑定路径(即“MyChild.Name”),并且对MyObject的引用,如何获得该Name属性的值?WPF - 从绑定路径获取属性值

MyObject 
    -MyChild 
    -Name 
+0

你能提供你想要如何使用这个方法的例子? – Rachel 2010-08-26 18:09:46

我找到了一个方法要做到这一点,但它很丑,可能不是很快......基本上,这个想法是创建一个与给定路径的绑定,并将其应用于依赖对象的属性。这样,结合确实检索值的所有工作:

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)); 
    } 
} 
+0

这似乎是很多机器来获得绑定的价值,但我想不出一个更好的通用代码解决方案。 +1和干杯。 – Berryl 2010-08-27 19:11:29

+0

非常好,谢谢托马斯!我需要这样的原因是因为我写了一个自定义标记扩展来加载图像。此扩展名具有图像名称的Name属性,我现在要将其绑定到使用标记扩展名的DataTemplate中的模型属性。然而,我不能绑定,因为名称不是DP,也不可能:(这是我能想到的唯一解决方案,所以我会试一试这个代码。谢谢。 – devdigital 2010-08-31 17:47:59

+0

这对我的需求非常合适(获取并设置给定绑定路径的视图模型的属性值)是否有类似的方法来获取将绑定到给定绑定路径的属性的_type_? – lesscode 2015-03-06 21:59:12

不知道你想要做什么,但如何(XAML或代码),但你总是可以命名对象

<MyObject x:Name="myBindingObject" ... /> 

的然后在代码中使用它

myBindingObject.Something.Name 

或在xaml

<BeginStoryboard> 
<Storyboard> 
    <DoubleAnimation 
     Storyboard.TargetName="myBindingObject" 
     Storyboard.TargetProperty="Background" 
     To="AA2343434" Duration="0:0:2" > 
    </DoubleAnimation> 
</Storyboard> 
</BeginStoryboard> 

我开发了一个nuget packagePather.CSharp已经做了你所需要的东西。

它包含一个Resolver类,它有一个Resolve方法,其行为类似于@ ThomasLevesque的方法GetValue
实施例:

IResolver resolver = new Resolver(); 
var o = new { Property1 = Property2 = "value" } }; 
var path = "Property1.Property2";  
object result = r.Resolve(o, path); //the result is the string "value" 

它甚至还支持经由索引或通过键字典访问收集访问
这些范例路径为:

"ArrayProperty[5]" 
"DictionaryProperty[Key]" 
+0

它支持访问显式实现的接口属性和隐藏属性吗? – Grx70 2016-01-13 07:21:38

+0

@ Grx70是的。它通过反射工作,所以如果该属性存在于对象上并且是公共的,它将获得它的值。 – Domysee 2016-01-13 08:52:50

我做这种方式。请让我知道这是一个可怕的想法,因为C#是只是一个副业了我,所以我不是专家objectToAddTo是类型的ItemsControl的:

BindingExpression itemsSourceExpression = GetaBindingExression(objectToAddTo); 
object itemsSourceObject = (object)itemsSourceExpression.ResolvedSource; 
string itemSourceProperty = itemsSourceExpression.ResolvedSourcePropertyName; 

object propertyValue = itemsSourceObject.GetType().GetProperty(itemSourceProperty).GetGetMethod().Invoke(itemsSourceObject, null); // Get the value of the property