如何在Xamarin PCL的hybridwebview中调用C#中的JavaScript?

时间:2016-11-19 06:43:43

标签: c# visual-studio xamarin xamarin.forms cross-platform

我对使用VS 2015的Xamarin Cross平台应用程序开发非常陌生。我的主要要求是从javascript函数获取值到C#,所以我开始使用HybridWebView。在官方指南(link-1link-2)的帮助下,我能够从javascript到C#获取值。

但是,现在我无法使用hybridWebView.Eval("jsFunction()")来调用来自C#的javascript,如上所述[{3}},但它现在显示错误 - HybridWebView does not contain definition for Eval

HybridWebView.cs

namespace Medical_Study
{
    public class HybridWebView : View
    {
        Action<string> action;
        public static readonly BindableProperty UriProperty = BindableProperty.Create(
          propertyName: "Uri",
          returnType: typeof(string),
          declaringType: typeof(HybridWebView),
          defaultValue: default(string));

        public string Uri
        {
            get { return (string)GetValue(UriProperty); }
            set { SetValue(UriProperty, value); }
        }

        public void RegisterAction(Action<string> callback)
        {
            action = callback;
        }

        public void Cleanup()
        {
            action = null;
        }

        public void InvokeAction(string data)
        {
            if (action == null || data == null)
            {
                return;
            }
            action.Invoke(data);
        }
    }
}

HybridWebViewPage.cs

namespace Medical_Study
{
    public class HybridWebViewPageCS : ContentPage
    {
        public HybridWebViewPageCS()
        {
            var hybridWebView = new HybridWebView
            {
                Uri = "index.html",
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            Padding = new Thickness(0, 20, 0, 0);
            Content = hybridWebView;
        }
    }
}

MCQ.xaml.cs

namespace Medical_Study
{
    public partial class MCQ : ContentPage
    {
        public MCQ()
        {
            InitializeComponent();

            //hybridWebView.RegisterAction(data => DisplayAlert("Alert", "Hello " + data, "OK"));
            hybridWebView.RegisterAction(data => jsTest(data));
        }

        public void jsTest(string jsReturn)
        {
            Debug.WriteLine(jsReturn);
            DisplayAlert("Test Title", "Test Message => " + jsReturn, "OK");
        }

        public void OnCallJavaScriptButtonClicked(object sender, EventArgs e)
        {
            // I am trying to trigger testFunction() but it's showing error - HybridWebView does not contain definition for Eval
            hybridWebView.Eval("testFunction()");
        }

    }
}

如何进行双方沟通(C#到JS和JS到C#)?

0 个答案:

没有答案