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

时间:2015-07-30 07:22:52

标签: c# wpf mvvm reflection

有没有办法通过使用字符串识别属性来设置属性?

例如,我有一个Visibility属性,如下所示:

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

绑定到XAML中的图标。由于每个图标的可见性是在运行时根据访问每个API的用户权限设置的,因此我有一个字典映射:

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"}
        },       
                        };    

如果列表中的任何API在权限中可用(我也从外部API接收),我将修改每个图标的可见性。例如,如果/ editFile可供用户使用,则将设置ModifyFilesIconVisibility:

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

否则,它们将保留为Visibility.Collapsed

由于这很乏味,我想知道我是否可以在映射中以某种方式使用属性本身的名称

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"}
        },       
                        };    

或类似的东西,然后使用Dictionary键将其设置为使用反射或其他任何内容可见。这可能吗?

1 个答案:

答案 0 :(得分:1)

 string propertyName = "ModifyFilesIconVisibility";

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

假设this指向具有ModifyFilesIconVisibility属性的实例