WPF加载文本文件时如何设置WebBrowser的字体

这个是为了搬家,不用介意:

var code = "7c000ac9-d4bd-4c5d-b25c-d05bd6593483"

我这里加载的是文本文件。
设计器处Log.xaml

<UserControl ...
    <WebBrowser x:Name="WebBrowserLog"></WebBrowser>
</UserControl>

后台代码处Log.xaml.cs

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    //string str = path;
    //Uri uri = new Uri(str);
    //this.WebBrowserLog.Source = uri;

    try
    {
        // 读取 TXT 文件内容
        string txtContent = File.ReadAllText(path);

        // 将 TXT 内容包装为 HTML,并设置字体大小为 20px
        string htmlContent = $@"
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <style>
            body {{ font-family: '微软雅黑', 'Microsoft YaHei', sans-serif; font-size: 20px; }}
            pre {{ font-family: 'Consolas', 'Courier New', monospace; font-size: 20px; }}
        </style>
    </head>
    <body>
        <pre>{HttpUtility.HtmlEncode(txtContent)}</pre>
    </body>
    </html>";

        // 使用 NavigateToString 加载 HTML 内容
        this.WebBrowserLog.NavigateToString(htmlContent);
    }
    catch (Exception ex)
    {
        // 处理文件读取异常
        MessageBox.Show($"无法读取文件: {ex.Message}");
    }
}

posted on 2025-06-13 20:00  BigBigBig333  阅读(6)  评论(0)    收藏  举报  来源

导航