Это еще один способ сделать это ...
AlertMessage.razor
<div style="border: 1px solid red; width: 500px; height:auto; margin: 3px;
padding:0px;">
<div style="height:auto; width:inherit; padding:5px; border: 1px solid
blue; text-align:right;">
<span style="float:left">@Title</span>
<a href="#" @onclick="@(() => Close.InvokeAsync(ID))"
role="button">X</a>
<div><input type="text" value="@content" /></div>
</div>
<div style="padding:25px; ">@ChildContent</div>
</div>
@code {
[Parameter]
public int ID { get; set; }
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback <int> Close {get; set;}
}
AlertMessageGroup.razor
@using Microsoft.AspNetCore.Components.CompilerServices;
<h3>AlertMessageGroup</h3>
@if (alerts.Count > 0)
{
<p>Contains @alerts.Count AlertMessage Components</p>
@foreach (var alert in alerts)
{
<p>Alert ID: @alert.ID</p>
}
}
<div>
@foreach (var alert in alerts)
{
@RenderAlert(alert);
}
</div>
@code {
List<Alert> alerts = new List<Alert>
{
new Alert{ ID = 1, Title = "First Message", Message = "This is my
first message" },
new Alert{ ID = 2, Title = "Second Message", Message = "This is
my second message" },
new Alert{ ID = 3, Title = "Third Message", Message = "This is my
third message" }
};
private RenderFragment RenderAlert(Alert alert) => builder =>
{
builder.OpenComponent(0, typeof(AlertMessage));
builder.AddAttribute(1, "ID", alert.ID);
builder.AddAttribute(2, "Title", alert.Title);
builder.AddAttribute(3, "ChildContent", (RenderFragment)((builder) =>
{
builder.AddContent(4, alert.Message);
}
));
builder.AddAttribute(5, "Close", EventCallback.Factory.Create<int>
(this, RemoveAlertMessage));
builder.CloseComponent();
};
public void RemoveAlertMessage(int ID)
{
alerts.Remove( alerts.Where(alert => alert.ID == ID).FirstOrDefault());
StateHasChanged();
}
public class Alert
{
public int ID { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
}
Использование
@page "/"
<AlertMessageGroup />