如何将值从页面传递到Blazor中的布局? [英] How to pass a value from a page to the layout in Blazor?

查看:90
本文介绍了如何将值从页面传递到Blazor中的布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布局( MainLayout.razor ),它有一个名为 ShowFooter 的标志.在某些页面上,我希望能够将该标记设置为 true ,而另一些页面设置为 false .

I have a layout (MainLayout.razor), and it has a flag called ShowFooter. On some pages, I want to be able to set that flag to true, and some others to false.

我还没有找到任何有关页面组件如何与布局通信的明确说明.该如何在Blazor中完成?

I haven't been able to find any clear instructions on how a page component can communicate with the layout. How should this be done in Blazor?

注意:您可能会说我应该有2种布局,一种有页脚,一种没有页脚,但这并不能真正解决我的问题,我希望能够显示和隐藏页脚在同一页面上的不同时间.另外,这只是需要在布局和页面之间进行通信的一种情况.还有无数其他人.

Note: You might say I should have 2 layouts, one with and one without the footer, but that wouldn't really solve my problem, I want to be able to show and hide the footer at different times on the same page. Plus, this is just one scenario where there is a need to communicate between the layout and the page. There are also countless others.

推荐答案

最简单的方法是在MainLaout组件中定义一个名为ShowFooter的公共布尔属性,如下所示:

The simplest way to do that is to define a public Boolean property named ShowFooter in the MainLaout component, as follows:

public bool ShowFooter {get; set;}

并通过将标记包装在其Value属性设置为 this CascadingValue 组件中,从而将对MainLaout组件的引用层叠到给定的组件,如下所示:

And to cascade a reference to MainLaout component to given components, by wrapping the markup within a CascadingValue component whose Value attribute is set to this, like this:

@inherits LayoutComponentBase


<CascadingValue Value="this">
     <div class="sidebar">
        <NavMenu />
    </div>
    <div class="main">
         <div class="content px-4">
            @Body
        </div>
    </div>
</CascadingValue>
@code
{
    public bool ShowFooter {get; set;}

     protected override void OnInitialized()
    {
      // Put here code that checks the value of ShowFooter and acts in 
      // accordance with your dear wishes

     }
}

在Index.razor中使用

Usage in Index.razor

@code{
     // Gets a reference to the MainLayout component
    [CascadingParameter]
    public MainLayout Layout { get; set; } 

    protected override void OnInitialized()
    {
        Layout.ShowFooter= true;
    
    }
}

这篇关于如何将值从页面传递到Blazor中的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆