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
相关产品推荐
相关产品推荐

