2016-07-04 34 views
0

Ich möchte auf ein Klassenmitglied durch Bindung zugreifen, aber ohne UI- oder XAML-Code.C# Zugriff auf ein Klassenmitglied durch Bindung

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 

Gibt es eine solche Methode?

+1

Haben Sie auf der [Dokumentation] nachlesen (https : //msdn.microsoft.com/en-us/library/cc838207 (v = vs.95) .aspx)? –

+0

Ja, aber die Dokumentation ist mit XAML oder Benutzeroberflächenelement (TextBlock) – skurton

Antwort

0

ich die Antwort gefunden, dank: How to get class members values having string of their names?

Keine Notwendigkeit der Binding-Klasse:

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; 
    } 
} 

Verbrauch:

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 
Verwandte Themen