我有一个文本 block 和一个网络浏览器控件。我有一个问题,例如,我的网络浏览器导航到 google.com。当网络浏览器导航到 google.com 时,我希望文本 block 将标题更改为 google.com。
请帮助我使用 C# 实现这一目标。
最佳答案
用 IE 测试
XAML:
<Grid>
<WebBrowser LoadCompleted="webBrowser1_LoadCompleted" Height="100" HorizontalAlignment="Left" Margin="73,72,0,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");
}
没有 dynamic
并且几乎没有任何异常处理:
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);
}
}
关于c# - 从 WebBrowser 控件中加载的文档中获取标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5548933/