Home > Mobile >  How to make a page visible using a variable on another page
How to make a page visible using a variable on another page

Time:11-16

I have a blazor application where I have the main window and other files which are the child windows.

I'm looking for a way for the main window button to open the child window, but even though the EnableConf value is true, the window won't open, I tried using StateHasChanged() and it still doesn't work.

CheckState.cs

public class CheckState {
    public bool EnableConf { get; set; } = false;
}

MainWindow.cs in MainWindow()

Collect.AddScoped<CheckState>();

Conf.razor

@inject AppBlaz.CheckState CheckState

if(CheckState.EnableConf) {
    <style>
    ...
    </style>
    ...
    <button @onclick="()=> CloseConf()">
    ...
    
}

@code {
    private void CloseConf() {
        CheckState.EnableConf = false;
    }
}

main.razor

@inject AppBlaz.CheckState CheckState
...
<button @onclick="()=> OpenConf()">
...

@code { 
    private void OpenConf() {
        CheckState.EnableConf = true;
    }
}

The child window close button works perfectly, the only problem is that the main window cannot open the child window.

Does anyone know how I can make this work correctly

CodePudding user response:

Presuming that somewhere in the main.razor you actually have placed the child window component (Conf.razor) to be hidden or displayed and there is no java script / third party lib that popups this window:

Add

[Parameter]
public bool CheckState {get; set;}
[Parameter]
public EventCallback<bool> CheckStateChanged { get; set; }

to your Conf.razor. Use this property as replacement for CheckState.EnableConf - if needed, then in OnAfterRender() override assign value to new property from currently used service (CheckState).

if(CheckState.EnableConf) becames if(CheckState).

In main.razor:
Repeat the above, but ommit [parameter] attribute for CheckState and drop whole CheckStateChanged including the [Parameter].
In place where the Conf.razor is initialized / put into actual ui code add
<Conf @Bind-CheckState=CheckState /> - now you will pass this newly created property down the line to child window.

In OpenConf() method change the newly created CheckState parameter instead of / in addition to CheckState.EnableConf.
CloseConf now should re

This should trigger the UI update. In case of emergency, add StateHasChanged() at the end of OpenConf() method.

Again, this should work (more or less, I typed in from memory) for standard blazor components.

  • Related