简体   繁体   中英

WPF two way binding infinite loop

since, functionality of Web Browser control is rather limited. I am trying to create a WebView control with two-way data binding using WindowsFormsHost . The url property of the control should be updated when I navigate to a new url. However, it seems to me that the property changes in an infinite loop and crashes the application. How can i solve this issue while allowing reloading of the same url?

Below is the code:

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

The quickest way would be a add a boolean "navigating" flag - eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM