Blazor, Use EventArgs with Bind:Set

64 views Asked by At

Suppose that we have a component named MyComponent.razor and it has a Text parameter and a TimedInput event:


[Parameter]
public string Text { get; set; } = "";

[Parameter]
public EventCallback<TimedInputEventArgs> TimedInput { get; set; }

The component starts a timer when the user starts typing and invokes the TimedInput event after a delay.

The TimedInputEventArgs contains the text that the user has typed and other optional information.

Other components need to bind to the Text parameter using bind:get and bind:set :

<MyComponent @bind-Text:event="TimedInput" @bind-Text:get=@(_input) @bind-Text:set="Set"></MyComponent>

@code {

private string _input = "";

   private void Set(TimedInputEventArgs args)
   {
      _input = args.CurrentText;
   }

}

The problem:
Text is string
The EventCallback is EventCallback<TimedInputEventArgs>
The blazor binding mechanism expects EventCallback<string> to work.

The compiler-generated BuildRenderTree based on the above code has this line in it:

__builder.AddAttribute(16, "TimedInput", RuntimeHelpers.TypeCheck<EventCallback<TimedInputEventArgs(EventCallback.Factory.Create<TimedInputEventArgs>(this, RuntimeHelpers.CreateInferredEventCallback(this, Set, (_input)))));
       

which shows an error message indicating that the Set method has an argument of type TimedInputEventArgs while it must have an argument of type string. (because _input is of type string)



I think it should be possible to invoke the event with whatever EventArgs instance.
Maybe the component wants to provide more information and not just the text that has changed so it will need some EventArgs instance to contain other fields too.
The blazor binding mechanism is forcing us to only be able to send the string.

One solution could be creating one EventCallback to notify the outside world about the change to the string and another EventCallback to send other things. Then invoking the two events one after the other. Which has it's own disadvantages.

Another solution is to change Text from string to some class that also contains the text and the extra information that is needed outside.

These solutions are problematic and not the thing that should be there.

0

There are 0 answers