Bind to WebBrowser’s Source Property

18 Sep

Unfortunately the Source property of the WebBrowser control is not a dependency property. Therefore it cannot be bound.
But there exists a workaround in order to bind a URI to a WebBrowser Control.
The workaround that exists is to create an attached property that can be bound and which changes reflect directly to the webbrowser’s source property.. This is done as follows:

public static readonly DependencyProperty BindableSourceProperty = DependencyProperty.RegisterAttached("BindableSource", typeof (string), typeof (WebBrowserUtility), new UIPropertyMetadata(null, OnBindableSourceChanged));

public static string GetBindableSource(DependencyObject obj)
    return (string)obj.GetValue(BindableSourceProperty);

public static void SetBindableSource(DependencyObject obj, string value)
    obj.SetValue(BindableSourceProperty, value);

private static void OnBindableSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    var browser = o as WebBrowser;
    if (browser == null)

    var uri = (string)e.NewValue;

        browser.Source = !string.IsNullOrEmpty(uri) ? new Uri(uri) : null;
    catch (ObjectDisposedException) {}

This attached property can be bound as follows:

<WebBrowser Name="browse" Utilities:WebBrowserUtility.BindableSource="{Binding Path=MyStrigUrlProperty}" />

Nice isn’t it?

Leave a comment

Posted by on September 18, 2012 in C-Sharp, WPF



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: