Navigate WebBrowser on mouse click through binding

2019-07-18 04:52发布

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?

3条回答
The star\"
2楼-- · 2019-07-18 05:20

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

查看更多
放荡不羁爱自由
3楼-- · 2019-07-18 05:28

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.

查看更多
Evening l夕情丶
4楼-- · 2019-07-18 05:31

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"

查看更多
登录 后发表回答