已经有一些很好的例子来说明如何通过以下方式创建“自定义控件” -
- 从 View 或现有的内置控件派生一个类,然后为每个平台创建一个自定义渲染器。
- http://blog.xamarin.com/using-custom-controls-in-xamarin.forms-on-android/
- http://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/
我想创建一个“复合自定义控件或用户控件”,其中包含在 XAML 中定义的多个元素(在共享代码中),然后使用渲染器进行自定义(比如调整每个平台的样式)。
请问有人有这样做的例子吗?一个带有可绑定标签和输入框的视图的简单示例应该足以显示主要原理。
这是我到目前为止所拥有的 -
定义了一个 ContentView 来表示我们的用户控件布局和内容。
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="News.Forms.VisualNewsContentView">
<ContentView.Content>
<StackLayout>
<Label x:Name="MyLabel" Text="Label"></Label>
<Entry x:Name="MyEntry" Text="Entry"></Entry>
</StackLayout>
</ContentView.Content>
</ContentView>
使用代码隐藏 -
public partial class VisualNewsContentView : ContentView
{
public VisualNewsContentView ()
{
InitializeComponent ();
}
// Not sure if I need this to access Entry ...
public Entry GetEntry ()
{
return MyEntry;
}
}
为该 ContentView 添加一个 Android 自定义渲染器,我如何访问和自定义 ContentView 的本机部分/控件?
[assembly:ExportRenderer (typeof(VisualNewsContentView), typeof(VisualNewsRenderer))]
namespace News.Forms.Android
{
public class VisualNewsRenderer: ViewRenderer
{
public VisualNewsRenderer () { }
protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
{
base.OnModelChanged (oldModel, newModel);
if (newModel != null) {
VisualNewsContentView newsContentView = newModel as VisualNewsContentView;
// i.e. How could I get hold of EditText etc so I could natively customise its appearance? When you use a built in renderer like EntryRenderer you can use Control to access native control.
Console.WriteLine (newsContentView.GetLabel ().Text);
EditText ed = (EditText)newsContentView.GetEntry ().???
}
}
}
}
只是无法将这些部分组合在一起工作,ContentView 似乎在页面上渲染得很好,但无法弄清楚如何在 viewrenderer 中访问其 Child Native 控件。
也很高兴展示如何将 Binding 用于 Label 和 Entry Text 值。
我不想为用户控件的每个标签/条目等定义自定义渲染器。