首页 > 解决方案 > 升级到 Xamarin.Forms 5.0 后,自定义控件中未调用 LayoutChildren 方法

问题描述

我创建了一个从ContentViewXamarin.Forms 扩展而来的自定义控件。我使用表单中的覆盖方法为某些场景布局了内容。LayoutChildren这在 XF 版本 4.8 之前运行良好。升级到 Xamarin.Forms 5.0 后,LayouChildren不会调用此覆盖方法,并且 UWP 中也不会显示内容。我怀疑,在 Xamarin.Forms 5.0 中,没有对 Content 执行布局/排列操作。

注意:如果我在 Grid 中添加相同的自定义控件,则会显示自定义控件的内容。

  1. 我只是创建了一个小的自定义控件来重现我的问题。在 Xamarin.Forms 中创建自定义控件

    public class CustomContentView: ContentView
     {
         public CustomContentView()
         {
         }
    
         protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
         {
             return base.OnMeasure(widthConstraint, heightConstraint);
         }
         protected override void LayoutChildren(double x, double y, double width, double height)
         {
             base.LayoutChildren(x, y, width, height);
         }
     }
    
  2. 在 UWP 渲染器项目中为此 Forms 控件创建了自定义渲染器。本机 UWP 控件扩展自ContentPresenter. 我已将表单内容转换为本机内容并设置为内容控件的内容。然后将内容控件分配给本机控件。

UWP 中的本机控制

public class CustomView : ContentPresenter
    {
        public CustomView()
        {
        }
    }

渲染器类

public class CustomRenderer : VisualElementRenderer<CustomControl.CustomContentView, CustomView>
    {
        private CustomView customView;
        public CustomRenderer()
        {
            this.AutoPackage = false;
        }
        protected override void OnElementChanged(ElementChangedEventArgs<CustomContentView> e)
        {
            if (e.NewElement == null)
            {
                return;
            }

            this.customView = new CustomView();
            this.customView.DataContext = this.Element.BindingContext;
            this.SetNativeControl(this.customView);

            if (Element.Content != null)
            {
                var renderer = Element.Content.GetOrCreateRenderer();
                var contentControl = new ContentControl();

                contentControl.Content = renderer.ContainerElement;
                this.customView.Content = contentControl;
            }
            base.OnElementChanged(e);
        }
    }

重现步骤

  1. 运行附加的示例(复制链接中给出的示例链接)
  2. 在我的自定义控件中添加了 Button 控件作为内容。但它不显示。

预期行为

应显示内容(按钮)

带有自定义控件的示例链接:

任何人请确认这是自定义控件(XF5.0)还是框架方面的问题?

标签: c#xamarinxamarin.formsxamarin.uwpcustom-renderer

解决方案


推荐阅读