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

我这里加载的是文本文件。

设计器处Log.xaml

csharp 复制代码
<UserControl ...
    <WebBrowser x:Name="WebBrowserLog"></WebBrowser>
</UserControl>

后台代码处Log.xaml.cs

csharp 复制代码
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}");
    }
}
相关推荐
✎ ﹏梦醒͜ღ҉繁华落℘8 小时前
开发WPF项目时遇到的问题总结
wpf
hqwest1 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars1 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest1 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest2 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0072 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业5 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103586 天前
WPF之绑定!
c#·wpf
DataIntel6 天前
wpf问题记录
wpf
蓝点lilac7 天前
C# WPF 内置解码器实现 GIF 动图控件
c#·.net·wpf·图像