First:
The answer to your question:
You must ensure the Webview2
control is initialized
before you can use it. You can do this in one of two ways, either call:
await MyWebView.EnsureCoreWebView2Async();
Or simply set the Source
property.
Next:
This is just a good advice. I never use 'NavigateToString', because having html in a C# string can quickly become 'messy'.
Instead I create a subfolder (called 'html'). Then I have a html
file, a css
file and a script
file inside this folder. Now I can edit the files directly and have intellisense and error checking at design time.
Remember: Click the files in 'Property Inspector
', then in properties window, select 'Copy to output directory
'. Here select: 'Copy if newer
'. Now the files will be copied to 'Bin' folder, so WebView2
can find them.
Now in your code, you simple set the WebView2's Source
property to the path of the html file, like this:
MyWebView.Source = new Uri(Path.Combine(Environment.CurrentDirectory, @"HtmlMyWebView.html"));
Note: This will automatically initialize the WebView2 and navigate to your html file.
In your html file, you can now include css and script files like you normally do for a webpage:
<html>
<head>
<meta charset="utf-8" />
<title>Whatever</title>
<link rel="stylesheet" href="MyWebView.css" type="text/css" />
<script type="text/javascript" src="MyWebView.js">
</script>
................
This is IMHO a much nicer way to use local html - much easier to maintain.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…