C# 用于阅读pdf的自定义Xamarin.Forms.WebView。带锚滚动
我试图找到在xamarin.forms上显示本地pdf文件的方法。 我找到了一个解决方案,实现了webview及其呈现的自定义实现: 主要代码是:C# 用于阅读pdf的自定义Xamarin.Forms.WebView。带锚滚动,c#,pdf,webview,xamarin.forms,xamarin.ios,C#,Pdf,Webview,Xamarin.forms,Xamarin.ios,我试图找到在xamarin.forms上显示本地pdf文件的方法。 我找到了一个解决方案,实现了webview及其呈现的自定义实现: 主要代码是: public class CustomWebView : WebView { public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(str
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
但现在我找不到向这个pdf文件添加锚点的方法,如本文所述:
我还尝试将此代码用于评估脚本:
private async void Scroll_Clicked(object sender, EventArgs e)
{
webView.Eval($"window.scrollTo(0, {x});");
}
它适用于默认webview,但不适用于自定义webview
也许有人知道其他方法可以滚动/设置锚定为pdf,并通过xamarin.forms链接到此锚定?
多谢各位
它适用于默认webview,但不适用于自定义webview
这不是由自定义webview引起的,因为渲染器在CustomWebViewRenderer
中为控件创建了一个新的UIWebview,请查看此代码部分:
if (Control == null) {
SetNativeControl (new UIWebView ());
}
因此,当执行webView.Eval($”window.scrollTo(0,{x});”)时,它不起作用代码>,因为此webview实际上不是UIWebview
解决方案
在CustomWebView中创建BindableProperty
public static readonly BindableProperty AnchorProperty = BindableProperty.Create<CustomWebView, float>(p => p.Anchor, default(float));
public float Anchor
{
get { return (float)GetValue(AnchorProperty); }
set { SetValue(AnchorProperty, value); }
}
在渲染器中获取值并使webview滚动
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName is "Anchor")
{
var customWebView = Element as CustomWebView;
float anchor = customWebView.Anchor;
Control.ScrollView.ContentOffset = new CoreGraphics.CGPoint(0, anchor);
}
}
夏科尔,非常感谢你!是的,它是这样工作的。先生,请再问一个问题:)您知道如何将此锚定绑定到pdf文档中所述的pdf部分或页面:因为设置定义的偏移量并滚动到它(而不是链接到定义的锚定或特定页面)是一种解决方法。检查此项,也许您会找到您想要的
public static readonly BindableProperty AnchorProperty = BindableProperty.Create<CustomWebView, float>(p => p.Anchor, default(float));
public float Anchor
{
get { return (float)GetValue(AnchorProperty); }
set { SetValue(AnchorProperty, value); }
}
private void Scroll_Clicked(object sender, System.EventArgs e)
{
webview.Anchor = 200;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName is "Anchor")
{
var customWebView = Element as CustomWebView;
float anchor = customWebView.Anchor;
Control.ScrollView.ContentOffset = new CoreGraphics.CGPoint(0, anchor);
}
}