簡體   English   中英

Xamarin Forms:如何通過屬性名獲取BindableProperty?

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

您好,我需要通過屬性名稱獲取 BindableProperty。 在此處輸入圖像描述

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

但我不想使用這種“if else”風格。 有沒有一種不需要判斷類型和名稱的通用方法?

嗨,我現在找到了解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM