2

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
touyets
  • 1,315
  • 6
  • 19
  • 34
  • Perhaps you can make the browser part of the viewmodel and use a contentpresenter to binds it's content to that property of your viewmodel? – Silvermind Sep 06 '13 at 10:19

3 Answers3

1

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
0

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

Alex Lebedev
  • 601
  • 5
  • 14
0

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"

Agilanbu
  • 2,747
  • 2
  • 28
  • 33