touyets
touyets

Reputation: 1325

Navigate WebBrowser on mouse click through binding

I have a WPF project using the MVVM model.

In my View, I have set up an invisible WebBrowser named myWebBrowser which is used to perform actions on the net (it seems that when I create the WebBrowser dynamically it does not work as intended).

I also have, in my View, a button which, when clicked, would normally launch a void action that is set up in the ViewModel. That's fine. The issue I am having is that I want that void to do some events such as:

myWebBrowser.Navigate(url)
myWebBrowser.LoadCompleted += WebBrowserLoaded;

and basically launch the process using the invisible WebBrowser that is in the View.

How can I achieve this as the ViewModel refuses for me to use a control name to reference it?

Upvotes: 2

Views: 2413

Answers (3)

user3591639
user3591639

Reputation: 11

Sheridan's answer is perfect but you might need to include the xmlns attribute

If you are using namespaces : xmlns:Attached="clr-namespace:foo.my.namespace"

Upvotes: 0

Sheridan
Sheridan

Reputation: 69959

You can create an Attached Property to do this for you:

public static class WebBrowserProperties
{
    public static readonly DependencyProperty UrlProperty = DependencyProperty.RegisterAttached("Url", typeof(string), typeof(WebBrowserProperties), new UIPropertyMetadata(string.Empty, UrlPropertyChanged));

    public static string GetUrl(DependencyObject dependencyObject)
    {
        return (string)dependencyObject.GetValue(UrlProperty);
    }

    public static void SetUrl(DependencyObject dependencyObject, string value)
    {
        dependencyObject.SetValue(UrlProperty, value);
    }

    public static void UrlPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        WebBrowser webBrowser = dependencyObject as WebBrowser;
        if (webBrowser != null && GetUrl(webBrowser) != string.Empty)
        {
            webBrowser.Navigate(GetUrl(webBrowser));
            webBrowser.LoadCompleted += WebBrowserLoaded;
        }
    }

    public static void WebBrowserLoaded(object sender, NavigationEventArgs e)
    {
    }
}

You could then use it like this:

<WebBrowser Attached:WebBrowserProperties.Url="{Binding YourUrlProperty}" />

To update the content, simply change the value of the YourUrlProperty property.

Upvotes: 1

Alex Lebedev
Alex Lebedev

Reputation: 609

try to use EventToCommand, if your webbrowser is hidden element in xaml.

Upvotes: 0

Related Questions