jeudi 3 septembre 2020

Using reflection to build UI controls

I have the following interface declared:

   public interface IDemoInterface
   {
      bool DemoBooleanProperty { get; set; }
      string DemoStringProperty { get; set; }
      IContainer RestrictiveContent { get; set; }
   }

and I implemented for this a method that uses reflection to build some UI controls based on the property type

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

      }

I managed to build the controls for the first ifs but now I want to use this function recursively to build the controls the same way but now for the IContainer interface which is a member of the initial interface and it seems that I cannot figure it out what should I pass to the BuildUIControls method in order to access the properties from this interface:

   public interface IContainer
   {
      TestEnum MandatoryEnum { get; set; }

      bool ReadOnly1Prop { get; set; }

      bool ReadOnly2Prop { get; set; }
   }

On the first call of this method I pass the data like this

         _demoInterface = new DemoInterfaceImplementation
         {
            DemoBooleanProperty2 = true,
            DemoStringProperty = "testString",
            RestrictiveContent = new ContainerInterfaceImplementation
            {
               MandatoryEnum = TestEnum.One, ReadOnly1Prop = true, ReadOnly2Prop = true
            }
         };
         vm.BuildUiControls(_demoInterface);

where the _demoInterface is declared as IDemoInterface.

Thanks for the help!





Aucun commentaire:

Enregistrer un commentaire