简体   繁体   English

WPF 中的 WebView2 和 MVVM - PostWebMessage

[英]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).我已经使用 angular 创建了一个 web 应用程序,现在我想使用 WebView2(不是电子)将它加载到 WPF 应用程序中。 That all works well.一切正常。 However, I also want to be able to send messages via the WebView2 using:但是,我还希望能够使用以下方法通过 WebView2 发送消息:

webView.CoreWebView2.PostWebMessageAsString(message)

I also want to adhere to MVVM.我也想坚持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.还有一个 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.现在我想在触发 ICommand 时从我的 ViewModel 调用 PostMessage(message),就像在 UI 上按下按钮时一样。 I know that the ViewModel shouldn't know about the View, so how is the best way to go about this?我知道 ViewModel 不应该知道 View,那么 go 的最佳方式是什么?

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.此外,我还想将我的 PostMessage(message) 方法移动到 WebViewService.cs class,但同样,服务如何知道 AngularView 中 webView 的 CoreWebView2 属性。

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:然后,您可以使用此接口注入视图 model:

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.在这种情况下,视图 model 只知道一个接口,对实际视图实现没有任何依赖性。 And you can easily mock the interface in your unit tests and benefit from everything else that the MVVM design pattern brings.您可以轻松地在单元测试中模拟接口,并从 MVVM 设计模式带来的其他一切中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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