Home > C#, MVVM, WinRT > How to use binding to set the WebView Url in a Windows Store app

How to use binding to set the WebView Url in a Windows Store app

11/06/2013

The WebView control that is part of WinRT doesn’t expose a property to directly set the Url that we want to navigate to. Instead, we need to use the Navigate method. This is annoying if we’re using the MVVM pattern.

So, a possible solution is to define an attached property that allow us to specify the Url via binding. Take a look to the following class:

public static class WebViewExtensions
{
    public static string GetUriSource(WebView view)
    {
        return (string)view.GetValue(UriSourceProperty);
    }

    public static void SetUriSource(WebView view, string value)
    {
        view.SetValue(UriSourceProperty, value);
    }

    public static readonly DependencyProperty UriSourceProperty = 
        DependencyProperty.RegisterAttached(
        "UriSource", typeof(string), typeof(WebViewExtensions), 
        new PropertyMetadata(null, OnUriSourcePropertyChanged));

    private static void OnUriSourcePropertyChanged(DependencyObject sender, 
        DependencyPropertyChangedEventArgs e)
    {
        var webView = sender as WebView;
        if (webView == null)
            throw new NotSupportedException();

        if (e.NewValue != null)
        {
            var uri = new Uri(e.NewValue.ToString());
            webView.Navigate(uri);
        }
    }
}

We’re defining a new Dependecy Property, UriSource, that, when set, simply calls the Navigate method on the WebView. In this way, in our XAML file we can write something like this:

<WebView 
    local:WebViewExtensions.UriSource="{Binding ItemUrl}" />

To create a binding between the WebView Url and a property called ItemUrl on our model.

Categories: C#, MVVM, WinRT
%d bloggers like this: