[英]How do you modify platform specific properties from a Xamarin.Forms application?
我有一個Xamarin.Forms
便攜式應用程序,其中包含帶有WebView
控件的Page
。
public class MainPage : ContentPage
{
private WebView webView;
public MainPage()
{
Content = (webView = new WebView());
}
}
WebView
類在每個平台上的實現方式有所不同-每個平台都有自己的一組額外屬性。 例如,在iOS上, WebView控件呈現為UIWebView
控件 ,該控件具有特定於平台的其他屬性 ,其中某些屬性不會通過WebView
類浮出水面。
當我的應用程序在iOS上運行時,我想在特定的WebView
控件上設置其中一些屬性。 (同樣,我也想對Android和UWP項目以及與其他非WebView的Xamarin.Forms控件進行相同的操作。)
那么,如何在Xamarin.Forms中設置這些平台特定控件的屬性?
發布答案以幫助他人,因為我終於弄清楚了。 –看來您需要實現自定義渲染器 。
本質上,在設備特定的項目中,您需要創建一個類,該類繼承給定控件的默認渲染器(此處有一些表 。
不幸的是,對於像WebView
這樣的更具體的控件,您將不得不自己解決。
最后,您必須添加一個程序集屬性以“導出”渲染器。
例如,iOS項目中的類可能如下所示:
using My.Project.iOS.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))]
namespace My.Project.iOS.Renderers
{
internal class CustomWebViewRenderer : Xamarin.Forms.Platform.iOS.WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
var view = NativeView as UIKit.UIWebView;
if (view != null)
{
view.ScrollView.ScrollEnabled = false;
view.ScrollView.Bounces = false;
}
}
}
}
注意:此渲染器將立即應用於iOS上渲染的所有WebView
控件。 因此,如果您只想將其應用於特定的設置,則需要一種方法向自定義渲染器表示要將附加設置應用於哪些設置; 我發現最簡單的方法是使用BindableProperty
(類似於WPF中的DependencyProperty
)。
為此,您可以在共享PCL項目中的某處聲明BindableProperty,如下所示:
namespace My.Project
{
public static class Properties
{
public static readonly BindableProperty EnableScrollingProperty = BindableProperty.Create
(
"EnableScrolling",
typeof(bool),
typeof(WebView),
true
);
}
}
您可以通過以下方法在WebView
對象上進行設置:
webView.SetValue(My.Project.Properties.EnableScrollingProperty, false);
並且可以修改渲染器的OnElementChanged
方法以獲取該屬性的值並進行如下檢查:
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
var enableScrolling = e?.NewElement?.GetValue(Properties.EnableScrollingProperty) as bool?;
if (enableScrolling.HasValue)
{
var view = NativeView as UIKit.UIWebView;
if (view != null)
{
view.ScrollView.ScrollEnabled = enableScrolling.Value;
view.ScrollView.Bounces = enableScrolling.Value;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.