如何在Xamarin.Forms uwp中设置WebView的动态高度?

时间:2019-05-23 10:19:20

标签: xamarin.forms xamarin.uwp

我正在Xamarin.Forms应用程序上工作,我想在uwp平台中动态设置Webview的高度作为宠物文本。

1 个答案:

答案 0 :(得分:0)

为您的网络视图定义Custom Renderer,然后注入JavaScript以计算内容的大小:

[assembly: ExportRenderer(typeof(CustomWebView), typeof(MyWebViewRenderer))]
namespace Demo.UWP
{
    public class MyWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.NavigationCompleted += Control_NavigationCompleted;
            }
        }

        private async void Control_NavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, Windows.UI.Xaml.Controls.WebViewNavigationCompletedEventArgs args)
        {
            var heightString = await Control.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
            int height;
            if (int.TryParse(heightString, out height))
            {
                Element.HeightRequest = height;
            }
        }
    }
}

您的表单页面的Xaml可能类似于:

<ScrollView>
    <StackLayout>
        <local:CustomWebView Source="https://www.microsoft.com"/>
        <!--Other controls-->
    </StackLayout>
</ScrollView>