2016-07-04 3 views
0

バインディングでクラスメンバーにアクセスしたいが、UIやXAMLコードは使用しない。C#バインディングでクラスメンバーにアクセスする方法

class Foo { 
    public int Value { get; set; } 
} 

class Bar { 
    public Foo foo { get; set; } 
} 

Bar bar = new Bar() { 
    foo = new Foo() { 
     Value = 2 
    } 
} 

Binding b = new System.Windows.Data.Binding("foo.Value"); 
b.Source = bar; 

// Now I want a method which returns bar.foo.Value, would be like that: 
int value = b.GET_VALUE(); // this method would return 2 

このような方法はありますか?

+1

あなたは[ドキュメント]をよく読んでいる(HTTPS ://msdn.microsoft.com/en-us/library/cc838207(v = vs95).aspx)? –

+0

はい、ドキュメントはXAMLまたはユーザーインターフェイス要素(TextBlock)を使用していますが、 – skurton

答えて

0

私は答えを見つけ、感謝に: How to get class members values having string of their names?

Bindingクラスの必要がありません:

public static class Extensions 
{ 
    public static object GetPropertyValue(this object Obj, string PropertyName) 
    { 
     object Value = Obj; 

     foreach (string Property in PropertyName.Split('.')) 
     { 
      if (Value == null) 
       break; 

      Value = Value.GetType().GetProperty(Property).GetValue(Value, null); 
     } 

     return Value; 
    } 
} 

使用法:

class Foo { 
    public int Value { get; set; } 
} 

class Bar { 
    public Foo foo { get; set; } 
} 

Bar bar = new Bar() { 
    foo = new Foo() { 
     Value = 2 
    } 
} 

bar.GetPropertyValue("foo.Value"); // 2 

bar.foo = null; 
bar.GetPropertyValue("foo.Value"); // null 
関連する問題