私はクロスプラットフォームのxamarinフォームアプリケーションを開発しています。ポータブルクロスプラットフォームアプリケーションを作成しました。私はwebviewでローカルhtmlページを開こうとしています。 angularjsからC#関数を呼び出すために、私はハイブリッドWebビューの概念を実装しました。Xamarin FormsのAngularJsスクリプトからC#関数を呼び出すPCLユニバーサルWindowsアプリケーション
私angularjsは、私はデータベースと通信するためにCommInterfaceクラスを使用していますAndroidのプロジェクトに好きなように
$scope.SyncServerJobs = function() {
//$scope.loadActList();
window.CommInterface.syncServerJobs("");
}
マイユニバーサルWindowsのプロジェクトで
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Windows.UI.Xaml.Controls.WebView>
{
public CommInterface communicator = new CommInterface();
const string JavaScriptFunction = "function invokeCSharpAction(data){window.external.notify(data);}";
const string SyncServerJobs = "function syncServerJobs(data){window.external.notify(data);}";
protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new WebView();
webView.Settings.IsJavaScriptEnabled = true;
SetNativeControl(webView);
}
if (e.OldElement != null)
{
Control.NavigationStarting -= OnWebViewNavigationStarted;
Control.NavigationCompleted -= OnWebViewNavigationCompleted;
Control.ScriptNotify -= OnWebViewScriptNotify;
}
if (e.NewElement != null)
{
Control.NavigationStarting += OnWebViewNavigationStarted;
Control.NavigationCompleted += OnWebViewNavigationCompleted;
Control.ScriptNotify += OnWebViewScriptNotify;
Control.Source = new Uri(string.Format("ms-appx-web:///Content//{0}", Element.Uri));
}
}
private void OnWebViewNavigationStarted(WebView sender, WebViewNavigationStartingEventArgs args)
{
if (Control != null && Element != null)
{
communicator = new CommInterface();
Control.AddWebAllowedObject("CommInterface", communicator);
}
}
async void OnWebViewNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
if (args.IsSuccess)
{
// Inject JS script
await Control.InvokeScriptAsync("eval", new[] { JavaScriptFunction });
await Control.InvokeScriptAsync("eval", new[] { SyncServerJobs });
}
}
void OnWebViewScriptNotify(object sender, NotifyEventArgs e)
{
Element.InvokeAction(e.Value);
}
}
マイcommInterfaceクラス
[AllowForWeb]
public sealed class CommInterface
{
readonly WeakReference<HybridWebViewRenderer> hybridWebViewRenderer;
public CommInterface()
{
}
public void syncServerJobs(string data)
{
HybridWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
{
hybridRenderer.Element.SyncServerJobs(data);
}
}
}
ファンクションポータブルライブラリのクラス。しかし、ユニバーサルWindowsプロジェクトでは、CSHARP CRUD機能を実行するためにCsharp関数と通信することができません。だから私の問題を一度見て、スクリプトからCSharp関数を呼び出すのを助けてください。どんな助けでもあなたにとても感謝します。