【问题标题】:C# How to access a class member by BindingC#如何通过绑定访问类成员
【发布时间】:2016-07-04 11:30:23
【问题描述】:

我想通过绑定来访问类成员,但没有任何 UI 或 XAML 代码。

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 

有这样的方法吗?

【问题讨论】:

  • 你读过documentation吗?
  • 是的,但文档包含 XAML 或用户界面元素 (TextBlock)

标签: c# binding


【解决方案1】:

我找到了答案,感谢: How to get class members values having string of their names?

不需要绑定类:

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

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多