我有一个文本块和一个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,0" Name="webBrowser1" VerticalAlignment="Top" Width="200" />
<Button Content="Go" Click="Button_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
码:
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");
}
Run Code Online (Sandbox Code Playgroud)
没有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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3817 次 |
| 最近记录: |