Considering the sample code below:
Counter.razor:
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
MainWindow.xaml:
<Window x:Class="WpfBlazor.MainWindow"
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:WpfBlazor"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow" Height="450" Width="800">
<Grid>
<blazor:BlazorWebView Name="webView" HostPage="wwwroot\index.html" Services="{DynamicResource services}">
<blazor:BlazorWebView.RootComponents>
<blazor:RootComponent Selector="#app" ComponentType="{x:Type local:Counter}" />
</blazor:BlazorWebView.RootComponents>
</blazor:BlazorWebView>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var serviceCollection = new ServiceCollection();
serviceCollection.AddWpfBlazorWebView();
Resources.Add("services", serviceCollection.BuildServiceProvider());
}
}
App.xaml.cs:
using System.Windows;
namespace WpfBlazor
{
public partial class App : Application
{
[STAThread]
public static void Main()
{
var app = new App();
app.InitializeComponent();
var window = new MainWindow();
window.Show();
app.Run();
}
}
}
It raises the following error on app.Run()
:
"EnsureCoreWebView2Async cannot be used before the application's event loop has started running."
It works if I do it in this way, but I can't, since it's a sample code, and in the real situation I need to separate instantiation and showing the window from the app.Run():
var window = new MainWindow();
app.Run(window);
I have tried calling the await window.webView.WebView.EnsureCoreWebView2Async(null);
in app startup and window loaded but it didn't work.
You should still start the app before showing the window. Call the
Run
method of theApp
in yourMain
method and then override theOnStartup
method of theApp
class to customize the initialization of the window: