csharp/Aaltuj/VxFormGenerator/VxFormGenerator.Core/VxFormElementLoader.cs

VxFormElementLoader.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using System;
using System.Linq.Expressions;
using VxFormGenerator.Core.Layout;

namespace VxFormGenerator.Core
{
    /// 
    /// The loader has the task to create a  with the correct bind-Value.
    /// It searches for a match in the  and will render the mapped component.
    /// 
    /// The type of the property
    public clast VxFormElementLoader : OwningComponentBase
    {
        [Inject]
        private IFormGeneratorOptions Options { get; set; }


        /// 
        /// Contains the Value binding methods and the key of the property.
        /// 
        [Parameter] public FormElementReference ValueReference { get; set; }

        protected override void OnInitialized()
        {
            base.OnInitialized();

        }

        /// 
        /// Create the  that is astociated with the 
        /// 
        /// 
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            base.BuildRenderTree(builder);

            // Get the registered FormElement component. 
            var elementType = Options.FormElementComponent;

            // When the elementType that is rendered is a generic Set the propertyType as the generic type
            if (elementType.IsGenericTypeDefinition)
            {
                Type[] typeArgs = { typeof(TValue) };
                elementType = elementType.MakeGenericType(typeArgs);
            }

            builder.OpenComponent(0, elementType);

            // Bind the value of the input base the the propery of the model instance
            builder.AddAttribute(1, nameof(FormElementBase.Value), ValueReference.Value);

            // Create the handler for ValueChanged. This wil update the model instance with the input
            builder.AddAttribute(2, nameof(FormElementBase.ValueChanged), ValueReference.ValueChanged);

            // if no explicit value expression create one based on the ValueReference
            if (ValueReference.ValueExpression == null)
            {
                // Create an expression to set the ValueExpression-attribute.
                var constant = Expression.Constant(ValueReference, ValueReference.GetType());
                var exp = Expression.Property(constant, nameof(ValueReference.Value));
                var lamb = Expression.Lambda(exp);

                builder.AddAttribute(4, nameof(FormElementBase.ValueExpression), lamb);
            }
            else
            {
                builder.AddAttribute(4, nameof(FormElementBase.ValueExpression), ValueReference.ValueExpression);
            } 

            builder.AddAttribute(6, nameof(FormElementBase.FormColumnDefinition), ValueReference.FormColumnDefinition);

            builder.CloseComponent();

        }
    }
}