简体   繁体   中英

WebView2 and MVVM in WPF - PostWebMessage

I have created a web application using angular and now I want to load it in a WPF application using WebView2 (not electron). That all works well. However, I also want to be able to send messages via the WebView2 using:

webView.CoreWebView2.PostWebMessageAsString(message)

I also want to adhere to MVVM. I've created a View:

    {
        public AngularView()
        {
            InitializeComponent();
            InitializeAsync();

        }
        
        public void PostMessage(string message)
        {
            webView.CoreWebView2.PostWebMessageAsString(message);
        }


        private async void InitializeAsync()
        {
            await webView.EnsureCoreWebView2Async();
        }
    }

And an AngularViewModel. Now I'd like to call PostMessage(message) from my ViewModel when a ICommand is triggered, like when button is pushed on the UI. I know that the ViewModel shouldn't know about the View, so how is the best way to go about this?

Furthermore, I'd also like to have moved my PostMessage(message) method to a WebViewService.cs class, but again, how does the service know about the CoreWebView2 property of the webView in the AngularView.

You should abstract away the view/control, for example by introducing an interface that the view implements:

public interface IWebComponent
{
    void Post(string message);
}

You could then inject the view model with this interface:

public AngularViewModel(IWebComponent webComponent)
{
    _webComponent = webComponent;
}

In this case the view model knows only about an interface and doesn't have any dependency upon the actual view implementation. And you can easily mock the interface in your unit tests and benefit from everything else that the MVVM design pattern brings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM