2015-07-06 116 views
0

因爲的功能網頁瀏覽器控件是相當有限的。我正嘗試使用WindowsFormsHost創建一個雙向數據綁定的WebView控件。當我導航到新的url時,應該更新控件的url屬性。但是,在我看來,屬性在無限循環中發生變化並導致應用程序崩潰。我怎樣才能解決這個問題,同時允許重新加載相同的網址?WPF雙向綁定無限循環

下面是代碼:

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

您是否嘗試過在檢查'UrlPropertyChangedCallback'你是否真的需要(從'Url'財產即是否'e.NewValue'實際上是不同的)分配新的價值? –

回答

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; 
}