我正在尝试创建一个 StackLayout
自定义渲染器,并根据 documentation ,基础渲染器是 ViewRenderer
.
所以我最终为 iOS 解决了这个问题:
public class MyCustomStackLayout : StackLayout { }
public class MyCustomStackLayoutRenderer : ViewRenderer<MyCustomStackLayout, UIView>
{
protected override void OnElementChanged(ElementChangedEventArgs<ExportableStackLayout> e)
{
base.OnElementChanged(e);
// some customizations here that don't mess with BackgroundColor at all
// removing all customizations doesn't fix the issue either.
}
}
我在我的 XAML 中像这样使用它:
<custom:MyCustomStackLayout BackgroundColor="Green">
</custom:MyCustomStackLayout>
几乎一切正常,渲染器已正确注册,其行为类似于
StackLayout
,甚至允许 Orientation
改变,但由于某种原因BackgroundColor
设置在我的 MyCustomStackLayout
, 被忽略,所以它总是透明的。我无法在代码库中找到原始渲染器的确切位置
StackLayout
已注册,因为它未在 AssemblyInfo 中注册使用其他渲染器,所以我不能 100% 确定我在这里做的是正确的事情。是否有我遗漏的东西正在制作
BackgroundColor
被忽视?我是否为 StackLayout
使用了正确的渲染器? ?有谁知道它究竟在哪里注册?更新:我知道如何实现 BackgroundColor,我实际上有兴趣了解为什么它首先不起作用。由于我使用了与原始 StackLayout 相同的渲染器,其中 already implements this .
最佳答案
这似乎是 ViewRenderer 的设计问题。您可以在渲染器中添加以下代码。
protected override void SetBackgroundColor(Color color)
{
base.SetBackgroundColor(color);
if (NativeView == null)
return;
if (color != Color.Default)
NativeView.BackgroundColor = color.ToUIColor();
}
关于xamarin - 如何在 Xamarin.Forms 中为 StackLayout 正确创建自定义渲染器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515869/