Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

blazor how to pass the variable value in the component to the MainLayout component

I created a project using the blazor server template that comes with vs 2019, how do I pass the currentCount property value in the Counter.razor component to a MainLayout.razor component?

And when the page is loaded, the currentCount value passed in the Mainlayout component is the same as the currentCount value in the Counter component. And when the currentCount value changes, the currentCount value in Mainlayout will also change.

MainLayout.razor:

@inherits LayoutComponentBase
<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <div class="main">
        <div class="top-row px-4 auth">
            <LoginDisplay />
        </div>
        <div class="content px-4">
            @Body
        </div>
    </div>
</div>

Counter.razor

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}
question from:https://stackoverflow.com/questions/65873050/blazor-how-to-pass-the-variable-value-in-the-component-to-the-mainlayout-compone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe you are looking for cascading parameters. Cascading values and parameters are a way to pass a value from a component to all of its descendants without having to use traditional component parameters.

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/cascading-values-and-parameters?view=aspnetcore-5.0

Example for origin of the cascading value will cascade to contained components.

<CascadingValue Value="@CurrentCount">
 @Body
</CascadingValue>

@code{
   int CurrentCount = 5;
}

The inner component should then decorate its property as following.

[CascadingParameter] int CurrentCount { get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...