如何在 Xamarin.Forms uwp 中设置 webview 的动态高度?
How to set dynamic height of webview in Xamarin.Forms uwp?
我正在开发一个 Xamarin.Forms 应用程序,我想在 uwp 平台中将 webview 的高度动态设置为 pet text。
为您的网络视图定义一个 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>
我正在开发一个 Xamarin.Forms 应用程序,我想在 uwp 平台中将 webview 的高度动态设置为 pet text。
为您的网络视图定义一个 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>