因为, Web浏览器控件的功能相当有限。我正在尝试使用WindowsFormsHost
创建一个带有双向数据绑定的WebView控件。当我导航到新的URL时,应该更新控件的url属性。但是,在我看来,属性在无限循环中发生变化并使应用程序崩溃。如何在允许重新加载相同网址的同时解决此问题?
以下是代码:
public class WebView : WindowsFormsHost
{
private WebBrowser webBrowser;
public static readonly DependencyProperty UrlProperty =
DependencyProperty.Register("Url", typeof(Uri), typeof(WebView), new FrameworkPropertyMetadata(default(Uri), UrlPropertyChangedCallback));
public Uri Url
{
get { return (Uri)GetValue(UrlProperty); }
set { SetValue(UrlProperty, value); }
}
private static void UrlPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as WebView).webBrowser.Url = e.NewValue as Uri;
}
public WebView()
{
webBrowser = new System.Windows.Forms.WebBrowser();
webBrowser.Navigating += webBrowser_Navigating;
Child = webBrowser;
}
private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
SetCurrentValue(UrlProperty, webBrowser.Url);
}
}
答案 0 :(得分:0)
最快的方法是添加一个布尔值"导航"旗帜 - 例如
bool navigating= false;
private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
navigating= true;
SetCurrentValue(UrlProperty, webBrowser.Url);
navigating= false;
}
private static void UrlPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (!navigating)
(sender as WebView).webBrowser.Url = e.NewValue as Uri;
}