0

I want to access a class member by binding, but without any UI nor XAML code.

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 

Is there such a method ?

skurton
  • 337
  • 2
  • 9

1 Answers1

0

I found the answer, thanks to: How to get class members values having string of their names?

No need of Binding class:

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

Usage:

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
Community
  • 1
  • 1
skurton
  • 337
  • 2
  • 9