gpt4 book ai didi

c# - 从 Xamarin Forms UWP 中的 Webview 获取内容高度

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:28 25 4
gpt4 key购买 nike

我正在尝试使用自定义呈现器获取在 Webview 中呈现的网页的高度。我已经设法连接到 Load_Completed 事件,该事件在页面完全呈现时正确触发,但似乎没有任何内容暴露高度。

我可以用什么来获得它?

提前致谢。

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms.Platform.UWP;
using Xamarin.Forms;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Controls;

[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(ExtendedViewWebRenderer))]
namespace Project.UWP.CustomRenderers
{
public class ExtendedViewWebRenderer : WebViewRenderer
{

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.LoadCompleted += Load_Completed;
}
}

private void Load_Completed(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
var _webView = (Windows.UI.Xaml.Controls.WebView)sender;
//Grab content's height here
}

}
}

最佳答案

这是我着陆的地方。对 UWP 知之甚少,所以请随时提出改进建议,但这似乎工作得很好。请注意,在我的例子中,我将一个 HTML 字符串从我的自定义控件传递到呈现/“导航”到,如果您要转到实际页面,只需使用 Control.Navigate(Uri source) .

public class ExtendedWebViewRenderer : ViewRenderer<ExtendedWebView, Windows.UI.Xaml.Controls.WebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<ExtendedWebView> e)
{
try
{
base.OnElementChanged(e);

if (e.OldElement != null && Control != null)
{
Control.NavigationCompleted -= OnWebViewNavigationCompleted;
}

if (e.NewElement != null)
{
if (Control == null)
{
SetNativeControl(new Windows.UI.Xaml.Controls.WebView());
}

Control.NavigationCompleted += OnWebViewNavigationCompleted;
}
}
catch (Exception ex)
{
Console.WriteLine("Error at ExtendedWebViewRenderer OnElementChanged: " + ex.Message);
}
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);

// update this based on your custom webview control and what you want it to do
if (Element is ExtendedWebView element && e.PropertyName.Equals(nameof(ExtendedWebView.Html)) && !string.IsNullOrWhiteSpace(element.Html))
Control.NavigateToString(element.Html);
}

private async void OnWebViewNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
if (!args.IsSuccess)
return;

var heightString = await Control.InvokeScriptAsync("eval", new[] {"document.body.scrollHeight.toString()" });
if (int.TryParse(heightString, out int height))
{
Element.HeightRequest = height;
}

var widthString = await Control.InvokeScriptAsync("eval", new[] {"document.body.scrollWidth.toString()" });
if (int.TryParse(widthString, out int width))
{
Element.WidthRequest = width;
}
}
}

关于c# - 从 Xamarin Forms UWP 中的 Webview 获取内容高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40029835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com