自定义 Xamarin.Forms.ListView 中的问题
任务:我需要实现一个控件,用于在 GridView 中显示项目,就像在 android 上一样。
问题的本质并尝试实现它:我创建了继承自 GridListBox Xamarin.Forms.ListView 的类 GridListBox。接下来我创建 GridListBoxRenderer 以 Xamarin.Forms.Platform.Android.ListViewRenderer 为例
我的网格列表框:
public class GridListBox : ListView
{
public static readonly BindableProperty ColumnCountProperty = BindableProperty.Create<GridListBox, int>(r => r.ColumnCount, 2);
public int ColumnCount
{
get { return (int)GetValue(ColumnCountProperty); }
set { SetValue(ColumnCountProperty, value); }
}
public static readonly BindableProperty HorizontalSpacingProperty = BindableProperty.Create<GridListBox, int>(r => r.HorizontalSpacing, 5);
public int HorizontalSpacing
{
get { return (int)GetValue(HorizontalSpacingProperty); }
set { SetValue(HorizontalSpacingProperty, value); }
}
public static readonly BindableProperty VerticalSpacingProperty = BindableProperty.Create<GridListBox, int>(r => r.VerticalSpacing, 5);
public int VerticalSpacing
{
get { return (int)GetValue(VerticalSpacingProperty); }
set { SetValue(VerticalSpacingProperty, value); }
}
}
GridListBox 的渲染器:
public class GridListBoxRenderer:NativeRenderer
{
private Cell cellFocused;
protected override void OnModelChanged(VisualElement oldModel, VisualElement newModel)
{
base.OnModelChanged(oldModel, newModel);
var realListView = (GridView)Control;
if (realListView == null)
{
realListView = new GridView(Context);
SetNativeControl((View)realListView);
}
cellFocused = (Cell)null;
realListView.Focusable = false;
realListView.DescendantFocusability = DescendantFocusability.AfterDescendants;
realListView.OnFocusChangeListener = (IOnFocusChangeListener)this;
realListView.SetNumColumns(((Controls.GridListBox) newModel).ColumnCount);
realListView.SetHorizontalSpacing(((Controls.GridListBox)newModel).HorizontalSpacing);
realListView.SetVerticalSpacing(((Controls.GridListBox)newModel).VerticalSpacing);
realListView.Adapter = new GridViewAdapter(Context, realListView, (Controls.GridListBox)newModel);
}
public override Size MinimumSize()
{
return new Size(40.0, 40.0);
}
}
然后乐趣开始了:如果以Xamarin.Forms.Platform.Android.ListViewAdapter (access as Internal)为例,实现 GridViewAdapter 很容易。要使用 ItemTemplate 实现公共 BaseAdapter.GetView (int position, View convertView, ViewGroup parent) 需要访问Xamarin.Forms.ListView.TemplatedItems 但它是内部的......
PS Xamarin 的开发人员如何计划使开发人员能够自定义 Xamarin.Forms 如果大多数属性具有内部访问权限...?
PPS 自定义 Xamarin.Forms.Page 也有类似的困难。Xamarin.Forms.Page.InternalChildren属性是内部的