4

Anyone knows why the below doesn't work? If I remove "onclick" event then it compiles & works as expected. Is that we are not allowed to use event within Reusable RenderFragments?

Env: ASP.NET Core 3.1 & Blazor Web Assembly

Thanks a lot for the help in advance!

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

enter image description here

@code {
    RenderFragment<(CategoryDto category, int myId)> rf =
      val => __builder =>
      {
        <h1 @onclick="()=> Console.WriteLine(val.category.Name)">Hello @val.category.Name, @val.myId</h1>
      };
}

1 Answer 1

2

The @onclick handler in your code will ultimately be created by the EventCallbackFactory. However, that factory needs a reference to 'this' which isn't supported in field initializers - hence you are receiving this error (and probably another one regarding 'this').

The solution is pretty simple. You just need to turn the field into a property like so:

RenderFragment<(CategoryDto category, int myId)> rf => val => __builder =>
{
    <h1 @onclick="() => Console.WriteLine(val.category.Name)">Hello @val.category.Name, @val.myId</h1>
};
Sign up to request clarification or add additional context in comments.

6 Comments

That worked. You probably wanna fix the typo "rf()" to "rf". Thanks a lot!
Notice than now it's not reusing rendering logic because you get new logic each time you use it. You don't get the extra performance.
@daniherrera I suppose what you could do is override OnInitialized() and then assign the RenderFragment there once.
Maybe a getter
@daniherrera can't I make it static so that it gives me the same instance all the time & I can still benefit from the performance? (Please note in the article I linked has the recommendation to make the RenderFragment static to be shared across multiple pages). Thank you!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.