我想在使用原生 android RecyclerView 作为渲染器的 Xamarin.Forms 中创建控件。
当我尝试创建包含标签或其他控件的单元格时,我的问题发生了,其 HorizontalOptions 不同于:Default、Fill 和 FillAndExpand。该标签只是不呈现自己(截图)。这是我的 .xaml 单元格代码
<?xml version="1.0" encoding="utf-8" ?>
<self:FormsRecyclerCell xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:self="clr-namespace:FormsRecyclerViewApp;assembly:FormsRecyclerViewApp" x:Class="FormsRecyclerViewApp.FormsRecyclerCellTemplate">
<Grid>
<Label Grid.Row="0" Text="{Binding .}" BackgroundColor="Blue" />
<Label Grid.Row="1" HorizontalOptions="Start" Text="Horizontal Start" BackgroundColor="AliceBlue"/>
<Label Grid.Row="2" HorizontalOptions="StartAndExpand" Text="Horizontal StartAndExpand" BackgroundColor="AliceBlue" />
<Label Grid.Row="3" HorizontalOptions="Fill" Text="Horizontal Fill" BackgroundColor="Aqua" />
<Label Grid.Row="4" HorizontalOptions="FillAndExpand" Text="Horizontal FillAndExpand" BackgroundColor="Aqua" />
<Label Grid.Row="5" HorizontalOptions="Center" Text="Horizontal Center" BackgroundColor="Bisque" />
<Label Grid.Row="6" HorizontalOptions="CenterAndExpand" Text="Horizontal CenterAndExpand" BackgroundColor="Bisque" />
<Label Grid.Row="7" HorizontalOptions="End" Text="Horizontal End" BackgroundColor="BlanchedAlmond" />
<Label Grid.Row="8" HorizontalOptions="EndAndExpand" Text="Horizontal EndAndExpand" BackgroundColor="BlanchedAlmond" />
<Label Grid.Row="9" Text="Horizontal Default" BackgroundColor="Azure"/>
<BoxView Grid.Row="10" BackgroundColor="Green" />
</Grid>
</self:FormsRecyclerCell>
为了在 RecyclerView 中渲染东西,我使用 CellContainer 创建 PlatformRenderer 并覆盖方法 OnLayout 和 OnMeasure
FormsRecyclerViewCellContainer.cs
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
using (var handler = new Handler(Looper.MainLooper))
{
handler.Post(() =>
{
double width = Context.FromPixels(r - l);
double height = Context.FromPixels(b - t);
Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion(this.view.Element, new XForms.Rectangle(0, 0, width, height));
this.view.UpdateLayout();
});
}
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (this.view == null || this.view.Element == null)
{
base.SetMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
return;
}
XForms.SizeRequest measure = this.view.Element.Measure(this.initialWidth, double.PositiveInfinity, XForms.MeasureFlags.IncludeMargins);
int height = (int)Context.ToPixels(this.fastCell.Height > 0 ? this.fastCell.Height : measure.Request.Height);
this.SetMeasuredDimension((int)Context.ToPixels(this.initialWidth), height);
}
我的问题:
- 从表单 .xaml 获取本机对象的最佳方法是什么?
- 为什么有些标签不呈现自己?
- 我应该怎么做才能正确渲染所有 VisualElemts?
随意下载我的示例项目。