You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# XAML中WebBrowser调用DocumentText嵌入YouTube视频报错问题

报错原因

你使用的是WPF XAML体系下的WebBrowser控件,该控件原生未提供DocumentText属性,这个属性是WinForm版本WebBrowser的专属API,因此触发编译报错。

修复步骤
  • 用WPF WebBrowser自带的NavigateToString()方法替代DocumentText赋值,该方法专门用来加载自定义HTML字符串内容
  • 修正代码中URL字符串缺少双引号的语法错误
修正后代码
using System.Text.RegularExpressions;

string _yUrl;
public string VideoID
{
    get
    {
        var yMatch = new Regex(@"http(?:s?)://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(&(amp;)?[\w\?=]*)?").Match(_yUrl);
        return yMatch.Success ? yMatch.Groups[1].Value : string.Empty;
    }
}
   
private void btnGo_Click(object sender, RoutedEventArgs e)
{
    _yUrl = "https://www.youtube.com/watch?v=cZ1Z0zZHktI";
    string htmlContent = String.Format("<meta http-equiv='X-UA-Compatible' content='IE=Edge'/><iframe width='100%' height='315'" +
    " src='https://www.youtube.com/embed/{0}?autoplay=0' frameborder='0' allow='accelerometer;" +
    " encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>", VideoID);
    webBrowser.NavigateToString(htmlContent);
}
补充说明

如果后续出现YouTube页面加载异常的问题,可切换为Chromium内核的WebView2控件获得更好的现代网页兼容性。

内容的提问来源于stack exchange,提问作者Squatch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 13:54:04