xamarin - 如何在 Xamarin.Forms 中为 StackLayout 正确创建自定义渲染器?

标签 xamarin xamarin.forms

我正在尝试创建一个 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/

相关文章:

ios - xamarin 构建在模拟器上通过但在真实设备上失败

android - Xamarin Android XamarinBuildAndroidAarRestore 任务无法从 Xamarin.Build.Download 加载

c# - Xamarin DependencyService : System. MissingMethodException:找不到 [Interface] 的默认构造函数

ios - MvvmCross Xamarin.Forms(iOS): Using a TabbedPage within a MasterDetail page

xamarin - 获取xamarin表单中的当前屏幕宽度

xamarin - 有没有办法可以将 FormattedText 包含在 Xamarin.Forms 的 .alert 中?

c# Xamarin 表单 : NavigationPage icon not showing

c# - HttpClient 不适用于 android

android - 将 Firebase Analytics 与 Xamarin Android 集成

c# - Xamarin Android 自定义线程类 block UI