'Set RenderFragment default content in code behind
I have the following code from an article that is placed inside a .razor file. How can the wig-pig code part be converted to a code behind .razor.cs file?
[Parameter] public RenderFragment<TItem> ItemTemplate { get; set; }
protected override void OnParametersSet()
{
if (ItemTemplate == null)
{
ItemTemplate = (item) => @:@{
<li @key=item>@item.ToString()</li>}
;
}
}
Solution 1:[1]
As per Mister Magoo's comment:
[Parameter]
public RenderFragment<TItem> ItemTemplate { get; set; }
= (TItem item) => (builder) =>
{
builder.OpenElement(0, "li");
builder.SetKey(item);
builder.AddContent(1, item.ToString());
builder.CloseElement();
};
Solution 2:[2]
A bit opinionated but I think you are exaggerating the 'code-behind concept' a little.
An ItemTemplate will only see use in the markup section, I would opt for a (small) @code section:
@code {
[Parameter]
public RenderFragment<TItem> ItemTemplate { get; set; } =
item => @<li @key=item>@item.ToString()</li>;
}
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 | Brian Parker |
| Solution 2 |
