.net 作为新窗口打开Razor组件

4sup72z8  于 2022-12-24  发布在  .NET
关注(0)|答案(1)|浏览(236)

我怎样才能打开新窗口与剃刀组件?我尝试打开新窗口与计数器()剃刀组件得到这个错误。

@code {
    private void openNewWindow(){
        Window secondWindow = new Window(new Counter());
        Application.Current.OpenWindow(secondWindow);

    }
}

错误CS1503:论据一:无法从“项目名称.页面.计数器”转换为“Microsoft.Maui.控件.页面”
这是毛伊岛Blazor应用程序项目,我想让用户打开图表面板到新窗口。

dphi5xsq

dphi5xsq1#

我挣扎了一会儿,找到了一个变通办法:https://github.com/dotnet/maui/issues/11746
此解决方法向blazor Router添加了一个属性来执行页面导航。
基于标准MAUI Blazor模板项目,执行以下操作:

    • 主剃刀**

添加StartPath属性并注入NavigationManager。当StartPath属性更改时,导航到新的StartPath。

@inject NavigationManager NavigationManager

<Router AppAssembly="@typeof(Main).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code
{
    [Parameter] public string StartPath { get; set; }

    protected override void OnParametersSet()
    {
        if (!string.IsNullOrEmpty(StartPath))
        {
            NavigationManager.NavigateTo(StartPath);
        }

        base.OnParametersSet();
    }
}
    • 主页. xaml**

x:Name添加到BlazorWebView组件

<BlazorWebView x:Name="blazorWebView" HostPage="wwwroot/index.html">
    <BlazorWebView.RootComponents>
        <RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
    </BlazorWebView.RootComponents>
</BlazorWebView>
    • 主页. xaml. cs**

StartPath属性添加到RootComponent

public partial class MainPage : ContentPage
{
    public MainPage(string startPath = null)
    {
        InitializeComponent();

        if (startPath != null)
        {
            blazorWebView.RootComponents[0].Parameters = new Dictionary<string, object>
            {
                { "StartPath", startPath },
            };
        }
    }
}

就是这样!
现在可以使用以下代码打开一个新窗口,指向 * Counter * 页面。

var counterWindow = new Window
{
    Page = new MainPage("/counter")
};

Application.Current.OpenWindow(counterWindow);

相关问题