2010-08-26 36 views
13

如果我有一個名爲MyObject的對象,該對象具有名爲MyChild的屬性,該屬性本身具有名爲Name的屬性。如果我擁有的是一個綁定路徑(即「MyChild.Name」),並且對MyObject的引用,如何獲得該Name屬性的值?WPF - 從綁定路徑獲取屬性值

MyObject 
    -MyChild 
    -Name 
+0

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

回答

19

我找到了一個方法要做到這一點,但它很醜,可能不是很快......基本上,這個想法是創建一個與給定路徑的綁定,並將其應用於依賴對象的屬性。這樣,結合確實檢索值的所有工作:

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

0

不知道你想要做什麼,但如何(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> 
3

我開發了一個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

0

我做這種方式。請讓我知道這是一個可怕的想法,因爲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