可以用MVVM的方式
将读取文件方法转为附加属性,将路径作为传递的参数。
using Microsoft.Toolkit.Wpf.UI.Controls;
using System.IO;
using System.Windows;
namespace 本地Html
{
public class ATCH
{
public static readonly DependencyProperty StaticHtmlProperty = DependencyProperty.RegisterAttached("StaticHtml", typeof(string), typeof(ATCH), new PropertyMetadata(null, new PropertyChangedCallback(StaticHtmlCallBack)));
private static async void StaticHtmlCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is WebView)||d==null)
return;
var web = d as WebView;
var path = e.NewValue.ToString();
if (string.IsNullOrWhiteSpace(path)||! File.Exists(path))
return;
var html = new FileStream(path, FileMode.Open);
var read = new StreamReader(html);
var StrHtml = await read.ReadToEndAsync();
web.NavigateToString(StrHtml);
read.Close();
html.Close();
}
public static void SetStaticHtml(DependencyObject d, string value) => d.SetValue(StaticHtmlProperty,value);
public string GetStaticHtml(DependencyObject d) => d.GetValue(StaticHtmlProperty).ToString();
}
}
XAML
通过绑定附加的值来进行控制网页访问的路径