Search code examples
asp.net-coreblazorblazor-server-sideblazor-webassembly

Blazor Dynamic Component @bind


I am trying to create a Dynamic component and in parameters I am trying to pass "@bind-Value" but its giving me exception saying bind-Value doesn't exist. My question is while creating a Dynamic component how we can specify bi-directional binding.

<DynamicComponent Type="context.Item.RenderComponent" Parameters="context.Item.RenderComponentParameters" />

and my parameter objects looks like this

     RenderComponentParameters = new Dictionary<string, object>()
 {
     { "@bind-Value", property },         
 },

Solution

  • @bind-Value directive is syntax shortcut for Value=".." and ValueChanged="..." and optionally ValueExpression="...", so you might want to add those parameters.

    1. Make sure your Component supports two way databinding by defining both, Value parameter and ValueChanged event callback parameter and optionally ValueExpression.

    2. Define the parameters' values in your RenderComponentParameters

      Expression<Func<string>> valueExpression = () => ...
      
      dictionary = new Dictionary<string, object>()
      {
        { "Value", property },         
        { "ValueChanged", EventCallback.Factory.Create<string>(this, val => ...)},
        { "ValueExpression", valueExpression } //optional
      },
      
      
      

    I recommend you to inspect C# code generated from .razor code (Razor syntax translated to C#). For example you might inspect how @bind-Value is translated, so that you can emulate it here.

    Add this to your .csproj: <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>, see this article