带有绑定的Source附加属性的WPF中的WebBrowser仅导航一次

时间:2016-09-07 10:49:09

标签: c# wpf xaml browser data-binding

我正在使用带有附加属性的WebBrowser控件绑定到ViewModel中的Uri属性,如this question

中所述

它可以工作,但在应用程序的每次启动时,浏览器只会导航一次。在第二次和进一步尝试它变得空(透明,而不是白色)。

视图模型:

public Uri BrowserUri
    {
        get
        {
            return GetBrowserUri();                
        }
    }

附属物:

public class AttachedUri
{
    public static readonly DependencyProperty AttachedUriProperty =
    DependencyProperty.RegisterAttached("AttachedUri", typeof(string), typeof(AttachedUri), new UIPropertyMetadata(null, AttachedUriPropertyChanged));

    public static string GetAttachedUri(DependencyObject obj)
    {
        return (string)obj.GetValue(AttachedUriProperty);
    }

    public static void SetAttachedUri(DependencyObject obj, string value)
    {
        obj.SetValue(AttachedUriProperty, value);
    }

    public static void AttachedUriPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        WebBrowser browser = o as WebBrowser;
        if (browser != null)
        {                
            string uri = e.NewValue as string;
            if (!String.IsNullOrEmpty(uri))
            {
                browser.NavigateToString("<html></html>"); // trying to refresh                    
                browser.Navigate(new Uri(uri));                    
            }                
        }
    }
}

XAML:

 <controls:WebBrowser at:AttachedUri.AttachedUri="{Binding BrowserUri}" Navigating="PDFBrowser_OnNavigating"/>

如上所示,我还试图在每次尝试导航时查看Navigating事件是否会触发。它每次Navigate都会触发,但NavigateToString只触发一次。

我需要浏览器在PDF文件中的不同命名目的地之间导航。

1 个答案:

答案 0 :(得分:0)

我决定每次需要导航时在静态边框中创建一个新浏览器。

<Border Grid.Row="1" at:AttachedUri.AttachedUri="{Binding BrowserUri}"/>

代码:

public static void AttachedUriPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        Border border = o as Border;            
        if (border != null)
        {                
            string uri = e.NewValue as string;
            if (!String.IsNullOrEmpty(uri))
            {
                Uri link = new Uri(uri);
                WebBrowser newBrowser = new WebBrowser();
                newBrowser.Navigate(link);
                border.Child = newBrowser;
            }                
        }
    }