Blazor 依赖注入妙用:巧设回调

前言

依赖注入我之前写过一篇文章,没看过的可以看看这个。

C# Blazor 学习笔记(10):依赖注入

依赖注入特性

  • 只能Razor组件中注入
  • 所有Razor组件在作用域注入的都是同一个依赖。作用域可以看看我之前的文章。

需求

在这里插入图片描述
Razor组件关系

  • Main:主页面
    • TreeItem(多个):树节点

我想让主逻辑写在Main里面,组件只做最简单的交互。所有的点击事件都以回调的形式。

解决方案

在Service中声明回调

/// <summary>
/// 节点回调状态
/// </summary>
public enum T_JointState
{
    
    
    Add,
    Delete,
    Up,
    Down,
    Update
}

/// <summary>
/// 节点添加回调
/// </summary>
public Action<int, T_JointState> CallBack {
    
     get; set; }

在子组件中使用回调

///注入依赖
 [Inject]
 private JointService jointService {
    
     get; set; }


 [Parameter]
 public int Index {
    
     get; set; }



 public void AddBtn()
 {
    
    
     MessageService.ShowMsg("添加");
     jointService.CallBack(Index,T_JointState.Add);
 }

 public void DeleteBtn()
 {
    
    
     MessageService.ShowMsg("删除");
     jointService.CallBack(Index, T_JointState.Delete);

 }

 public void UpBtn()
 {
    
    
     MessageService.ShowMsg("上移");
     jointService.CallBack(Index, T_JointState.Up);

 }

 public void DownBtn()
 {
    
    
     MessageService.ShowMsg("下移");
     jointService.CallBack(Index, T_JointState.Down);

 }
 public void EditBtn()
 {
    
    
     MessageService.ShowMsg("编辑");
     jointService.CallBack(Index, T_JointState.Update);

 }

在父组件中设置回调

[Inject]
private JointService jointService {
    
     get; set; }


 protected override void OnAfterRender(bool firstRender)
 {
    
    
     if (firstRender)
     {
    
    
         jointService.CallBack = JointNodeCallBack;
         StateHasChanged();
     }
     base.OnAfterRender(firstRender);
 }
      /// <summary>
      /// 设置回调函数
      /// </summary>
      /// <param name="index"></param>
      /// <param name="state"></param>
      public void JointNodeCallBack(int index,T_JointState state)
      {
    
    
          MessageService.ShowMsg("回调成功!");
      }

示意图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44695769/article/details/132429599