WPF JS调用WPF方法传递信息

一、建立js命令回调wpf类

[ComVisible(true)]  //这句要加到类定义前,可与COM通信
    public class ObjectForScriptingHelper
    {
        WIndex mainWindow;

        public ObjectForScriptingHelper(WIndex main)
        {
            mainWindow = main;
        }

        #region JS调WinForm方法的接口
        /// 
        /// PDjt页面的js回传消息
        /// 
        /// 
        public void pdjtListMessage(string paran)
        {
            PDjtListViewModel.ToJt(paran);
        }

        #endregion
    }

注:如果不把该类独立出来,在window或page里面直接写,会提示:

执行了QueryInterface调用,请求提供 COM 可见的托管类“Cloud.MainWindow”的默认IDispatch 接口。不过,由于该类没有显式默认接口,并且是从非 COM 可见的类“System.Windows.Window”派生的,QueryInterface 调用将失败。这样做的目的是避免非 COM 可见的基类受 COM 版本规则的约束。

二、Page.xaml.cs页面添加监听

private void web_djtlist_Navigated(object sender, NavigationEventArgs e)
        {
            WinUtils.SuppressScriptErrors((WebBrowser)sender, true);

            HTMLDocument doc = web_djtlist.Document as HTMLDocument;
            IHTMLWindow2 win = (IHTMLWindow2)doc.parentWindow;
            //假设把alert消息传出来处理
            string s = @"function toWpf(str){window.external.pdjtListMessage(str);}";
            win.execScript(s, "javascript");
            web_djtlist.ObjectForScripting = new ObjectForScriptingHelper(WinUtils.GetAncestor(this));

        }

注意:pdjtListMessage与第一大点接收类里面的接收方法名称一致,否则无法接收消息

你可能感兴趣的:(WPF)