简体   繁体   English

仅使用字符串名称设置属性

[英]Setting Property using only string name

Is there a way I can set a property by identifying it using a string? 是否可以通过使用字符串识别属性来设置属性?

For example, I have a Visibility property that looks something like this: 例如,我有一个Visibility属性,看起来像这样:

public Visibility ModifyFilesIconVisibility
        {
            get { return modifyFilesIconVisibility; }
            set
            {
                SetProperty(ref modifyFilesIconVisibility, value, () => ModifyFilesIconVisibility);
            }
        }

which is bound to an icon in XAML. 绑定到XAML中的图标。 Since each icon's visibility is set during runtime based on user authority to access each APIs, I have a Dictionary mapping: 由于每个图标的可见性是在运行时根据访问每个API的用户权限设置的,因此我有一个Dictionary映射:

public static Dictionary<string, List<string>> Views = new Dictionary<string, List<string>> {
                        {
    "ModifyFiles", 
            new List<string>{"/editFile", "/deleteFile", "/cutFile", "/copyFile"}
        }, 
                        {
    "CRUDLogs", 
            new List<string>{"/writeLog", "/deleteLog", "/viewLog", "/searchLog"}
        },       
                        };    

and if any of the APIs in the List is available in the authority (which I receive from an external API as well), I will modify the visibility of each icon. 并且如果列表中的任何API在授权机构中都可用(我也从外部API接收到),则我将修改每个图标的可见性。 So for example, if /editFile is available to the user, the ModifyFilesIconVisibility will be set: 因此,例如,如果/ editFile对用户可用,则将设置ModifyFilesIconVisibility:

foreach (string api in APIMappings.Views["ModifyFiles"])
{
  if (URLs.Contains(api)) 
  {
   this.ModifyFilesIconVisibility = Visibility.Visible;
   break;
  }
}

Otherwise they are left as Visibility.Collapsed . 否则,它们将保留为Visibility.Collapsed

Since this is tedious, I was wondering if I can somehow use the name of the property itself in the mapping 由于这很乏味,所以我想知道是否可以以某种方式在映射中使用属性本身的名称

public static Dictionary<string, List<string>> Views = new Dictionary<string, List<string>> {
                        {
    "ModifyFilesIconVisibility", 
            new List<string>{"/editFile", "/deleteFile", "/cutFile", "/copyFile"}
        }, 
                        {
    "CRUDLogsIconVisibility", 
            new List<string>{"/writeLog", "/deleteLog", "/viewLog", "/searchLog"}
        },       
                        };    

or something like that, and then use the Dictionary key to set it to visible using reflection or anything else. 或类似的东西,然后使用Dictionary键通过反射或其他方式将其设置为可见。 Is this possible? 这可能吗?

 string propertyName = "ModifyFilesIconVisibility";

 var property = TypeDescriptor.GetProperties(this).Find(propertyName, false);
 property.SetValue(this, Visibility.Visible);

assuming this points to the instance with ModifyFilesIconVisibility property 假设this指向具有ModifyFilesIconVisibility属性的实例

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

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