繁体   English   中英

C#如何通过绑定访问类成员

[英]C# How to access a class member by Binding

我想通过绑定访问类成员,但没有任何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 

有这种方法吗?

我找到了答案,这要归功于: 如何获得具有其名称字符串的类成员值?

不需要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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM