【问题标题】:Open Razor Component as new window在新窗口中打开 Razor 组件
【发布时间】:2022-12-24 01:22:41
【问题描述】:

如何打开带有剃须刀组件的新窗口? 我尝试使用 Counter() razor 组件打开新窗口,但出现此错误。

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

    }
}

错误CS1503:参数 1:无法从“ProjectName.Pages.Counter”转换为“Microsoft.Maui.Controls.Page”

这是 Maui Blazor App 项目,我想允许用户将图表面板打开到新窗口。

【问题讨论】:

  • 欢迎,请将您的代码作为文本而不是图片插入,谢谢。
  • 你想打开一个新选项卡,还是与 .NET MAUI 有关?
  • @AlirezaK 更新为代码。
  • @MarvinKlein 这与 .net Maui 相关,而不是 web。我想打开基于剃须刀组件的新窗口。

标签: .net macos razor blazor


【解决方案1】:

我挣扎了一会儿,在这里找到了解决方法: https://github.com/dotnet/maui/issues/11746

此解决方法向执行页面导航的 blazor Router 添加了一个属性。

基于标准的 MAUI Blazor 模板项目,执行以下操作:

主.razor

添加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

BlazorWebView组件中添加x:Name

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

MainPage.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 },
            };
        }
    }
}

而已!

您现在可以使用以下代码打开一个新窗口,指向柜台页。


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

Application.Current.OpenWindow(counterWindow);

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多