Search code examples
c#wpfrazorblazor

Navigate From WPF Window to a Razor page (Blazor Hybrid)


I have a dotnet-7 windows application which uses Wpf + Blazor.

My Problem is that I cant navigate from a window to a razor page

my MainWindow.xaml:

<Button Content="Open" Click="OpenOnClick" />

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddWpfBlazorWebView();
#if DEBUG
        serviceCollection.AddBlazorWebViewDeveloperTools();
#endif
        Resources.Add("services", serviceCollection.BuildServiceProvider());

        InitializeComponent();
    }
    private void OpenOnClick(object sender, RoutedEventArgs e)
    {
        new EditingWindow().Show();
    }
}

EditingWindow.xaml:

<Window x:Class="CodeEditor.EditingWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:blazor="clr-namespace:Microsoft.AspNetCore.Components.WebView.Wpf;assembly=Microsoft.AspNetCore.Components.WebView.Wpf"
        xmlns:local="clr-namespace:CodeEditor"
        mc:Ignorable="d"
        Title="EditingPage" Height="450" Width="800">
    <Grid>
        <blazor:BlazorWebView HostPage="wwwroot/index.html" Services="{DynamicResource services}">
            <blazor:BlazorWebView.RootComponents>
                <blazor:RootComponent Selector="#app" ComponentType="{x:Type local:IndexEditor}" />
            </blazor:BlazorWebView.RootComponents>
        </blazor:BlazorWebView>
    </Grid>
</Window>

and the razor page itself is just a <h1> tag and an empty code behind:

IndexEditor.razor IndexEditor.razor.cs

and the index.html is the regular blazor boilerplate:

...head

<body>

<div id="app">Loading...</div>

<div id="blazor-error-ui">
    An unhandled error has occurred.
    <a href="" class="reload">Reload</a>
    <a class="dismiss">🗙</a>
</div>

<script src="_framework/blazor.webview.js" autostart="false"></script>

</body>

when i click the button, the window shows up, but it is empty, it has the title which I set in the EditingWindow.Xaml which was EditingPage, but it is empty, I think the problem is that it cant serve the razor page but IDK why, and I also tried different ways of navigation but non of them made any difference.


Solution

  • You need to add the "services" ServiceProvider resource to the EditingWindow that hosts the BlazorWebView:

    public partial class EditingWindow : Window
    {
        public EditingWindow()
        {
            InitializeComponent();
    
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddWpfBlazorWebView();
            Resources.Add("services", serviceCollection.BuildServiceProvider());
        }
    }