css Blazor服务器在MainLayout中更改顶行,razor

tzcvj98z  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(148)

Blazor Server和.Net 6
在Counter.razor页面中我添加了一个按钮,这个按钮调用了一个方法ChangeColor(),我想用这个方法来改变MainLayout. razor中顶行div的颜色。

柜台剃须刀

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

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

@code {
    private int currentCount = 0;

    private void ChangeColor()
    {
        *from_here_i_will_like_to_change_TOP_ROW_DIV*
    }
}

字符串

MainLayout.razor@TopRowColor

@inherits LayoutComponentBase

<PageTitle>BlazorApp1</PageTitle>

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <main>
        <div class="top-row px-4" style="background-color: @TopRowColor">
            <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
        </div>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>

@code {
    [Parameter]
    public string TopRowColor { get; set; } = "red";  
  
}


我的问题是,我如何从计数器页面更改上栏的颜色
x1c 0d1x的数据

jq6vz3qz

jq6vz3qz1#

1.首先,创建一个保存共享状态的服务

public class TopRowStateService
 {
     public string TopRowColor
     {
         get;
         private set;
     } = "red"; // default color

     public event Action OnChange;

     public void SetTopRowColor(string color)
     {
         TopRowColor = color;
         NotifyStateChanged();
     }

     private void NotifyStateChanged() => OnChange?.Invoke();
 }

字符串
1.在Startup.cs或Program.cs中注册此服务(取决于您的Blazor Server版本),以便将其注入组件:
第一个月
1.在MainLayout.razor中注入TopRowStateService,并将其属性用于div的样式:
`

@inject TopRowStateService TopRowState

<div class="top-row px-4" style="background-color: @TopRowState.TopRowColor">
</div>

@code {
    protected override void OnInitialized()
    {
        TopRowState.OnChange += StateHasChanged;
    }

    public void Dispose()
    {
        TopRowState.OnChange -= StateHasChanged;
    }
}

个 1.在Counter.razor中注入服务并使用它来改变颜色:

@inject TopRowStateService TopRowState
<button class="btn btn-primary" @onclick="ChangeColor">Click me</button>
    @code {

    private void ChangeColor()
    {
        TopRowState.SetTopRowColor("newColor"); 
    }
}

`个

相关问题