Search code examples
asp.net-coreblazorblazor-webassemblymaui-blazor

A shared public static variable does not change synchronously in all razor pages (in Blazor)


I defined a static class in order to share data among different razor pages. Here is the class:

namespace BlazorTest
{
    public static class General
    {
        public static int number;
    }
}

This is my parent razor:

@page "/"
<button @onclick="()=>Increase()">Increase</button>
<br />
Here is parent page.
<br />
@General.number
<br />
<Child />

@code{
    protected override void OnInitialized()
    {
        base.OnInitialized();
        General.number = 0;
    }
    void Increase()
    {
        General.number++;
        StateHasChanged();
    }
}

This is my child razor:

<button @onclick="()=>Increase()">Increase</button>
<br />
Here is child page.
<br />
@General.number

@code {
    void Increase()
    {
        General.number++;
        StateHasChanged();
    }
}

When I click the button four times in the child page, the output is:

Here is parent page.
0
Here is child page.
4

Then I click the parent button once, it becomes:

Here is parent page.
5
Here is child page.
4

Can I synchronize the public static class?


Solution

  • This is because the the click in child doesn't call statehaschanged in parent, and vice versa。 You could create an Action parameter in the child and bind to StateHasChanged in the parent. Try following:
    parent:

    @page "/"
    <button @onclick="()=>Increase()">Increase</button>
    <br />
    Here is parent page.
    <br />
    @General.number
    <br />
    <Child a_child_action="()=>{this.StateHasChanged();}" />
    
    @code{
        protected override void OnInitialized()
        {
            General.number = 0;
        }
        void Increase()
        {
            General.number++;
        }
    }
    

    Child:

    <button @onclick="()=>Increase()">Increase</button>
    <br />
    Here is child page.
    <br />
    @General.number
    
    @code {
        [Parameter] public Action a_child_action { get; set; }
    
        void Increase()
        {
            General.number++;
            a_child_action.Invoke();
        }
    }