首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用反射生成UI控件

使用反射生成UI控件
EN

Stack Overflow用户
提问于 2020-09-03 13:33:21
回答 1查看 50关注 0票数 1

我声明了以下接口:

代码语言:javascript
复制
   public interface IDemoInterface
   {
      bool DemoBooleanProperty { get; set; }
      string DemoStringProperty { get; set; }
      IContainer RestrictiveContent { get; set; }
   }

为此,我实现了一种基于属性类型使用反射构建某些UI控件的方法。

代码语言:javascript
复制
      public void BuildUiControls<T>(T instance, bool groupData = false)
      {
         foreach (var propertyInfo in instance.GetType().GetProperties())
         {
            if (propertyInfo.PropertyType == typeof(bool))
            {
               ...
            }

            if (propertyInfo.PropertyType == typeof(string))
            {
              ...
            }
            
            if (propertyInfo.PropertyType.IsEnum)
            {
               ...
            }

            if (propertyInfo.PropertyType == typeof(IContainer))
            {
               BuildUiControls(???, true);
            }
         }

      }

我成功地为第一个ifs构建了控件,但是现在我想递归地使用这个函数来以相同的方式构建控件,但现在使用的是IContainer接口,它是初始接口的一个成员,而且似乎无法计算出应该传递给BuildUIControls方法的内容,以便从这个接口访问属性。

代码语言:javascript
复制
   public interface IContainer
   {
      TestEnum MandatoryEnum { get; set; }

      bool ReadOnly1Prop { get; set; }

      bool ReadOnly2Prop { get; set; }
   }

在该方法的第一次调用中,我传递如下数据

代码语言:javascript
复制
         _demoInterface = new DemoInterfaceImplementation
         {
            DemoBooleanProperty2 = true,
            DemoStringProperty = "testString",
            RestrictiveContent = new ContainerInterfaceImplementation
            {
               MandatoryEnum = TestEnum.One, ReadOnly1Prop = true, ReadOnly2Prop = true
            }
         };
         vm.BuildUiControls(_demoInterface);

其中_demoInterface被声明为IDemoInterface。

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-03 14:12:40

以下是有关的守则:

代码语言:javascript
复制
if (propertyInfo.PropertyType == typeof(IContainer))
{
   BuildUiControls(???, true);
}

您需要做的是获取该属性的值,然后可以使用该值递归调用您的方法。例如:

代码语言:javascript
复制
if (propertyInfo.PropertyType == typeof(IContainer))
{
    var containerValue = propertyInfo.GetValue(instance) as IContainer;
    BuildUiControls(containerValue);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63724785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档