加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从WebBrowser控件中加载的文档中获取标题

发布时间:2020-12-16 01:42:48 所属栏目:百科 来源:网络整理
导读:我有一个文本块和一个webbrowser控件.我有一个问题,例如,我的webbrowser导航到google.com.当webbrowser导航到google.com时,我希望文本块将标题更改为google.com. 请帮我用c#实现这个目标. 解决方法 用IE测试 XAML: Grid WebBrowser LoadCompleted="webBrows
我有一个文本块和一个webbrowser控件.我有一个问题,例如,我的webbrowser导航到google.com.当webbrowser导航到google.com时,我希望文本块将标题更改为google.com.

请帮我用c#实现这个目标.

解决方法

用IE测试

XAML:

<Grid>
    <WebBrowser LoadCompleted="webBrowser1_LoadCompleted" Height="100" HorizontalAlignment="Left" Margin="73,72,0" Name="webBrowser1" VerticalAlignment="Top" Width="200" />
    <Button Content="Go" Click="Button_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
</Grid>

码:

private void webBrowser1_LoadCompleted(object sender,NavigationEventArgs e)
{
    dynamic doc = webBrowser1.Document;
    this.Title = doc.Title;
}

private void Button_Click(object sender,RoutedEventArgs e)
{
    webBrowser1.Navigate("http://google.com");
}

没有动态,几乎没有任何异常处理:

private void webBrowser1_LoadCompleted(object sender,NavigationEventArgs e)
{
    Object doc = webBrowser1.Document;
    this.Title = GetPropertyValue<string>(doc,"Title");
}

private T GetPropertyValue<T>(object obj,string propertyName)
{
    Type objectType = obj.GetType(); 
    PropertyInfo propertyInfo = objectType.GetProperty(propertyName);
    Type propertyType = propertyInfo.PropertyType;
    if(propertyType == typeof(T))
    {
        object propertyValue = (T)info.GetValue(obj,null);   
        return value;
    }
    else
    {
        throw new Exception("Property " + propertyName + " is not of type " + T);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读