Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a two-way binding in blazor using the RenderTreeBuilder?

I would like to know how to implement a two-way-binding in blazor using the RenderTreeBuilder. Therefore I created the following minimalistic example to discuss about a solution

<MudForm @ref="@_Form" @bind-IsValid="@IsValid">@ChildContent</MudForm>

@code {
    [Parameter]
    public bool IsValid { get; set; }

    [Parameter]
    public EventCallback<bool> IsValidChanged { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    private MudForm _Form;
}

I would like to reimplement the blazor code concerning the MudForm using the RenderTreeBuilder. I face difficulties as I want to implement the bind-IsValid-attribute. I have no idea on how to implement this two-way-binding. My implementation so far looks like following

    private RenderFragment formControl => (builder) =>
    {
        builder.OpenComponent<MudForm>(0);
        builder.AddAttribute(1, nameof(MudForm.IsValid), IsValid);
        builder.AddAttribute(2, nameof(MudForm.IsValidChanged), EventCallback.Factory.CreateBinder(this, value => IsValid = value, IsValid));
        builder.AddAttribute(3, nameof(MudForm.ChildContent), ChildContent);
        builder.AddComponentReferenceCapture(4, (value) => { _Form = (MudForm)value; });
        builder.CloseComponent();
    };

Is the use of the EventCallback.Factory correct? Does anyone have an idea on how to implement such a two way binding to a property using the RenderTreeBuilder?

like image 294
Marcel Müller Avatar asked Sep 20 '25 16:09

Marcel Müller


1 Answers

I figured out the solution by checking the generated file. Here is what I did:

  1. I added following attribute to the .csproj-file of the corresponding project and built the project.

    <PropertyGroup>
      <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    </PropertyGroup>
    
  2. Go to the generated files (e.g. /obj/Debug/net6.0/generated/....)

  3. Go to the corresponding file ending on .g.cs and check the generated code of the RenderTreeBuilder.

  4. Following code was generated by the razor compiler

    builder.AddAttribute(2, nameof(MudForm.IsValidChanged), EventCallback.Factory.Create<bool>(this, value => { IsValid = value; }));
    
like image 198
Marcel Müller Avatar answered Sep 23 '25 05:09

Marcel Müller