'Is there a way to alter ChildContent in Blazor

I'd like to alter ChildContent my component receives from the parent like this:

<Markdown>
  # Title

  Some _Content_
</Markdown>

To interpret this content I would need to do something like Markdown.ToHTML(@ChildContent).

But as ChildContent is not a string, I need some means to access the ChildContent and retrieve it as string. Is this possible and how can it be done? Any other idea to solve this?



Solution 1:[1]

This isn't impossible but it's not a great way to go.

In order to take a render fragment and produce HTML, it needs to be run through a renderer. This isn't a particularly simple thing to achieve. If you want to see an example you can look at the Test Renderer produced by Steve Sanderson for his unit testing prototype.

You could have a go at creating your own renderer but I would suggesting considering a different approach.

Solution 2:[2]

Most probably you have already found a solution, but take a look at the code snippet bellow (.NET 5.0):

var builder = new RenderTreeBuilder();
builder.AddContent(0, this.ChildContent);
var frame = builder.GetFrames().Array.FirstOrDefault(x => new[] 
{
  RenderTreeFrameType.Text, 
  RenderTreeFrameType.Markup 
}.Any(t => x.FrameType == t));
var value = frame?.MarkupContent;

Adding content to builder adds two frames, a region one and a text/markup one, depending on whether ChildContent contains plain text of HTML. Instead of guessing however, it is safer to use FirstOrDefault.

NB: This is kind of a hack and is not guaranteed that would work in future version of Blazor. I haven't used it with Blazor 6.0 or 7.0 (in preview, yet to be released) but I am able to retrieve the content of, pardon me, ChildContent.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Sainty
Solution 2 Alexander Christov