如果您定期使用自定義渲染器,則可以創建自定義視圖渲染器,如this。例如:
在PCL:
public class NewView : View
{
}
在Android平臺上,第一下創建/資源/佈置的配置是這樣的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/tv"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="this is new view." />
<Button android:id="@+id/btn"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="change text" />
</LinearLayout>
然後創建渲染NewView
這樣的:
public class NewViewRenderer : ViewRenderer
{
private TextView tv;
private Android.Widget.Button btn;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var context = Xamarin.Forms.Forms.Context;
LayoutInflater minflater = context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
var view = minflater.Inflate(Resource.Layout.newview, this, false);
tv = view.FindViewById<TextView>(Resource.Id.tv);
btn = view.FindViewById<Android.Widget.Button>(Resource.Id.btn);
SetNativeControl(view);
}
if (e.OldElement != null)
{
btn.Click -= Btn_Click;
}
if (e.NewElement != null)
{
btn.Click += Btn_Click;
}
}
private void Btn_Click(object sender, EventArgs e)
{
tv.Text = "Text changed!";
}
}
最後在ContentPage
中使用此視圖來製作它像一個頁面:
<ContentPage.Content>
<local:NewView />
</ContentPage.Content>
對於iOS平臺,應該有設置ViewController
作爲一個視圖渲染本地控制的方法。但是我對iOS不熟悉,你可以試試看。