【问题标题】:Passing values to generic list from one Blazor component to another将值从一个 Blazor 组件传递到另一个通用列表
【发布时间】:2020-06-26 05:35:02
【问题描述】:

我在一个名为RowData 的通用列表中有两个变量,它有两个变量,分别是RowPositionRowInfo,它们将在服务器端提供数据。

通用列表将被导入一个函数,该函数将构建表单并使用传递给它的数据。

我的问题是我在服务器端使用什么来允许传递数据?例如:

RowPosition : RowInfo
1 : blahyes
2 : blahno
3 : blahlol
4 : blahblah

【问题讨论】:

    标签: c# blazor


    【解决方案1】:

    您没有发布足够多的代码,让我无法继续提出建议,但组件之间有几种通信方式。

    您可以使用级联值,子组件将能够像这样引用父组件:

    <CascadingValue Value="GalleryManager">
        <ArtistListViewer></ArtistListViewer>
        <ImageListViewer></ImageListViewer>
    </CascadingValue>
    

    这里我的 ArtistListViewer 和 ImageListViewer 组件可以通过这个属性引用画廊管理器:

    [CascadingParameter]
    GalleryManager GalleryManager { get; set; }
    

    如果使用过于频繁,这可能会导致性能问题,具体取决于您网站的繁忙程度。

    我写了一篇关于另一种方式的博文:

    使用接口在组件之间进行通信 https://datajugglerblazor.blogspot.com/2020/01/how-to-use-interfaces-to-communicate.html

    如果您发送任何复杂的东西,我更喜欢上面的方法,其中父对象是 IBlazorComponentParent,子对象是 IBlazorComponent。

    Nuget 包:DataJuggler.Blazor.Components

    以下是您可以像这样在孩子上设置 Parent 属性的方法:

     <Login OnLogin="LoginComplete" Parent=this></Login>
    

    Parent=这是可能的,因为我的登录组件是一个 IBlazorComponent,而我的索引页面是一个 IBlazorComponentParent。

    child setter 像这样向 Parent 注册:

    public IBlazorComponentParent Parent
    {
        get { return parent; }
        set 
        { 
            // set the parent
            parent = value;
    
            // if the value for HasParent is true
            if (HasParent)
            {
                // Register with the parent to receive messages from the parent
                Parent.Register(this);
            }
        }
    }
    

    Index 页面上的 Register 事件将子项存储为属性:

    public void Register(IBlazorComponent component)
    {
        // If the component object exists
        if (NullHelper.Exists(component, Children))
        {
            // If this is the Login component
            if (component.Name == "Login")
            {
                // Set the Signup control
                this.Login = component as Login;
            }
    
            // add this child
            Children.Add(component);
        }
    }
    

    此时,我的 Login 组件知道了它的父组件,并且父 Index 页面将 Login 组件作为变量。

    然后你可以发送任何你喜欢的消息。

    在我的登录完成方法中,我向父母发送了一条消息:

    // if the Parent exists
    if (HasParent)
    {
        // create a message to send
        Message message = new Message();
    
        // Set the text
        message.Text = loginResponse.Message;
    
        // Send a message to the parent
        Parent.ReceiveData(message);;
    }
    

    上面我只是传入了文本,但是还有一个NamedParameters集合,你可以传递任何类型的数据(对象)。

    如果有兴趣,这里有一个完整的工作示例和教程:

    代码 https://github.com/DataJuggler/BlazorImageGallery

    视频 https://youtu.be/3xKXJQ4qThQ

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多