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
?
I figured out the solution by checking the generated file. Here is what I did:
I added following attribute to the .csproj-file of the corresponding project and built the project.
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
Go to the generated files (e.g. /obj/Debug/net6.0/generated/....)
Go to the corresponding file ending on .g.cs and check the generated code of the RenderTreeBuilder
.
Following code was generated by the razor compiler
builder.AddAttribute(2, nameof(MudForm.IsValidChanged), EventCallback.Factory.Create<bool>(this, value => { IsValid = value; }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With