Blazor笔记-Component interaction-Sharing data




2024年3月7日 发布。
2023年8月1日 迁移笔记到博客。

Component interaction-Sharing data approaches

In Blazor, data can be shared between components using three approaches:

  • CascadingParameter.
  • Parameter.
  • Transfer service.

CascadingParameter approach

CascadingParameter is a feature in Blazor that allows passing data from an ancestor component to its descendant components in a hierarchical structure. It is not able to pass data between sibling components. The following image illustrates how data flows through a component tree using CascadingParameter:



<CascadingValue Value="@MyParameter" Name="MyParameter">

public int MyParameter { get; set; } = 0;


  public string MyProperty { get; set; };


<CascadingValue Value="@Style1" Name="Style1">
    <CascadingValue Value="@Style2" Name="Style2">

  public string Style1 { get; set; } = "Test Value";
  public string Style2 { get; set; } = "Test Value";

Parameter approach

Parameter is a feature for transmitting data from a parent component to its direct child components. However, it is essential to note that this approach does not allow passing data to sibling components or the children of the direct child. The following image illustrates how data flows through a component tree using Parameter:


In your child component, declare public properties that will receive the parameters passed from the parent component. You can use the [EditorRequired] attribute to mark a parameter as required. Additionally, you can set default values for the parameter by defining it in the getter and setter.

public string RequiredInputParameter { get; set; } = "";


public EventCallback ExampleInstanceChanged { get; set; }

Capture unmatched values

[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> AdditionalAttributes { get; set; } = new();

Transfer service approach

Transfer service is a useful approach when you want all of your components to share a common data source or adopt a "single source of truth" approach. It is not restricted by the component tree and can pass data across all components within your website. The following image illustrates how data flows through a component tree using transfer service:


This approach allows you to centralize the data management and keep the state of your components consistent, making your application more maintainable and easier to test.

  • Declare a transfer service
  • Consume a transfer service
posted @ 2024-03-07 15:32  重庆熊猫  阅读(5)  评论(0编辑  收藏  举报