简体   繁体   中英

How to convert Xamarin.Forms WebView object to platform-specific WebView object?

I have a WebView object created in Xamarin.Forms:

WebView webView = new WebView {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand
        };

I need to do some platform-specific operations on this object: call some functions that aren't available in Xamarin.Forms because of different nature of this on different platforms.

The problem is, when I pass the Xamarin.Forms object:

public interface IWebViewCallCSharp
{
    void passWebView(WebView webView);
}

I can do on "native side" exactly the same things as I could in Xamarin.Forms. How can I get some platform-specific functions of WebView on each platform? How to convert this to this ?

You will need to implement a so-called custom renderer. Start here: Implementing a HybridWebView .

In short you will need to:

  1. Create the HybridWebView custom control.
  2. Consume the HybridWebViewfrom Xamarin.Forms.
  3. Create the custom renderer for the HybridWebView on each platform.

In the last step you need to

  1. Create a subclass of the ViewRenderer class that renders the custom control. The first type argument should be the custom control the renderer is for, in this case HybridWebView. The second type argument should be the native control that will implement the custom view.
  2. Override the OnElementChanged method that renders the custom control and write logic to customize it. This method is called when the corresponding Xamarin.Forms custom control is created.
  3. Add an ExportRenderer attribute to the custom renderer class to specify that it will be used to render the Xamarin.Forms custom control. This attribute is used to register the custom renderer with Xamarin.Forms.

The starting point where you begin using native controls is the OnElementChanged override.

protected override void OnElementChanged (ElementChangedEventArgs<NativeListView> e)
{
  base.OnElementChanged (e);

  if (Control == null) {
    // Instantiate the native control and assign it to the Control property
  }

  if (e.OldElement != null) {
    // Unsubscribe from event handlers and cleanup any resources
  }

  if (e.NewElement != null) {
    // Configure the control and subscribe to event handlers
  }
}

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