Merlin04,下面的代码 sn -p 演示了如何做到这一点。请注意,这实际上是一个非常简单的示例,但它显示了当需要在远程组件之间进行通信时应该如何编码。
这是代码,复制并运行它,如果您有更多问题,请随时提问。
MessageService.cs
public class MessageService
{
private string message;
public string Message
{
get => message;
set
{
if (message != value)
{
message = value;
if (Notify != null)
{
Notify?.Invoke();
}
}
}
}
public event Action Notify;
}
注意:服务是一个普通的类...它为其他对象提供服务,应该在 Startup.ConfigureServices 方法中将它添加到 DI 容器中,以使其可供请求的客户端使用。在 ConfigureServices 方法中添加:
services.AddScoped<MessageService>();
注意:如您所见,我定义了一个 Action 类型的事件委托,当用户在 Component3 中的文本框中键入文本时,它会从属性的 set 访问器调用。触发此委托会导致 Components3 输入的文本显示在 Index 组件中,该组件是 Component2 的父级(参见下面的代码)。
Index.razor
@page "/"
@inject MessageService MessageService
@implements IDisposable
<p>I'm the parent of Component2. I've got a message from my grand child:
@MessageService.Message</p>
<Component2 />
@code {
protected override void OnInitialized()
{
MessageService.Notify += OnNotify;
}
public void OnNotify()
{
InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
MessageService.Notify -= OnNotify;
}
}
注意我们直接绑定MessageService.Message属性,但是必须调用StateHasChanged方法来刷新文本的显示。
Component2.razor
<h3>Component2: I'm the parent of component three</h3>
<Component3/>
@code {
}
Component3.razor
@inject MessageService MessageService
<p>This is component3. Please type a message to my grand parent</p>
<input placeholder="Type a message to grandpa..." type="text"
@bind="@MessageService.Message" @bind:event="oninput" />
请注意,在 Component3 中,我们将 MessageService.Message 绑定到一个文本框,并且每次按下键盘时都会发生绑定(输入事件与更改
事件)。
仅此而已,希望对您有所帮助,请随时提出任何问题。