xamarinpropertiesbindable

Xamarin Forms: How to get the BindableProperty by the property name?


Hi, i need to get the BindableProperty by the property name. enter image description here

public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    if(typeof(Entry) == bindableObj.GetType()) {
        if("Text" == propertyName) {
            return (Entry.TextProperty);
        }
        if("TextColor" == propertyName) {
            return (Entry.TextColorProperty);
        }
    }
    return (null);
}

But i do not want to use this "if else" style. Is there a general way that I don't need to judge the type and name?


Solution

  • Hi, I found the solution now:

    public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
        Type type = bindableObj.GetType();
        FieldInfo fieldInfo;
        while(null == (fieldInfo = type.GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public))) {
            type = type.BaseType;
        }
        if(null == fieldInfo) {
            throw (new Exception("Can not find the BindableProperty for " + propertyName));
        }
        return ((BindableProperty)(fieldInfo.GetValue(bindableObj)));
    }