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}");
    }
}
相关推荐
凌镜icecraft3 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
光泽雨7 天前
控件Password附加属性
wpf
samble12 天前
从零搭建半导体设备上位机(十二):参数设置页,表单校验、范围校验与配方联动
wpf·数据校验·validationrule
samble20 天前
从零搭建半导体设备上位机(九):拖拽与交互,Adorner、DragDrop 与晶圆拖放信息
wpf·拖拽·adorner
郝学胜-神的一滴21 天前
AI 编程智能体 27:吃透MCP通信机制
人工智能·python·langchain·wpf·numpy·scikit-learn
波力海苔夹心脆67522 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
陈仓主教22 天前
# WPF CheckBox 控件详解与使用—WPF 中的控件(6)--复选框控件(CheckBox)
wpf
光泽雨24 天前
WPF 音视频四大核心方案对比
wpf·音视频
浪扼飞舟25 天前
WPF(数据绑定)
wpf
samble1 个月前
从零搭建半导体设备上位机(四):单实例、启动流程与配置文件,App 里那 526 行到底在干什么
wpf·配置文件·单实例