C# 如何获取文档';从wpf中的Web浏览器控件中删除标题
我已在TabControl中创建了Web浏览器控件。我想将TabItem的标题设置为Web浏览器的文档标题。 我在WebBrowser的导航事件中使用了以下代码C# 如何获取文档';从wpf中的Web浏览器控件中删除标题,c#,wpf,wpf-controls,webbrowser-control,tabcontrol,C#,Wpf,Wpf Controls,Webbrowser Control,Tabcontrol,我已在TabControl中创建了Web浏览器控件。我想将TabItem的标题设置为Web浏览器的文档标题。 我在WebBrowser的导航事件中使用了以下代码 dynamic doc = tabBrowser.Document; //tabBrowser is the name of WebBrowser Control tab.Header = doc.Title; //tab is the name of the Tab Item 但这段代码并没有像它应该的那样工作
dynamic doc = tabBrowser.Document; //tabBrowser is the name of WebBrowser Control
tab.Header = doc.Title; //tab is the name of the Tab Item
但这段代码并没有像它应该的那样工作。标题只会在少数站点中更改。
如何将tabItem的标题设置为文档的标题值
以下是导航功能:
public void tabBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
urlTextBox.Text = tabBrowser.Source.ToString();
myHistory.addToHistory(tabBrowser.Source.ToString());
BookMarks.addBookmark(tabBrowser.Source.ToString());
dynamic doc = tabBrowser.Document;
tab.Header = doc.Title;
}
在我的代码中,我使用了WebBrowser的LoadCompleted事件。可能在您的导航事件文档中仍然没有准备好,文档标题不正确或为空
private void MyWebBrowser_LoadCompleted_1(object sender, NavigationEventArgs e)
{
try
{
MyTextBox.Text = MyWebBrowser.Source.ToString();
Title_doc.Content = ((dynamic)MyWebBrowser.Document).Title;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
这个可以用
var docTitle = document.getElementsByTagName("title")
.Cast<IHTMLElement>()
.FirstOrDefault().innerText;
var docTitle=document.getElementsByTagName(“标题”)
.Cast()
.FirstOrDefault().innerText;
当操作过程中文档发生更改时(操作无法完成,不支持异常,原因为8070000c),(动态)文档
强制转换至少会失败,如果用户点击链接太快就会发生这种情况
根据问题更新2链接找到另一个合理的解决方案
TitleChanged事件似乎工作可靠,因此从那里改编代码,并向该事件添加处理程序
wbEvents.TitleChange += new SHDocVw.DWebBrowserEvents_TitleChangeEventHandler(OnWebBrowserTitleChanged);
处理程序只有一个参数,新标题为字符串
void OnWebBrowserTitleChanged(string title)
{
// Set title where you want
}
有点重,但我需要这两个来工作
该链接代码还存在其他问题,例如在WebBrowser的每个LoadCompleted事件上再次添加事件处理程序您是否确定每次页面都已完全呈现和加载?请注意,任何动态更改其标题的网站也将不起作用,请您也提供一些周边代码好吗?e、 g.执行导航和处理导航事件的代码?以下是导航函数
public void tabBrowser\u navigated(object sender,System.Windows.navigation.NavigationEventArgs e){urlTextBox.Text=tabBrowser.Source.ToString();myHistory.addToHistory(tabBrowser.Source.ToString());BookMarks.addBookmark(tabBrowser.Source.ToString());dynamic doc=tabBrowser.Document;tab.Header=doc.Title;}