【问题标题】:How to create custom controls in Xamarin?如何在 Xamarin 中创建自定义控件?
【发布时间】:2019-12-06 01:25:03
【问题描述】:

我正在尝试为 Xamarin 表单创建一些自定义控件...

这些控件应该像一组其他控件一样工作。例如 Label + Entry 作为一个控件插入到页面中。

我在这里创建了一个继承自 View 类的简单控件。

这是一个有两个标签的类的例子。在这个类中,除了这些标签之外,还应该插入其他控件。

public class Ton : View
{
    public Ton() : base()
    {
        Label L;            
        L = new Label();
        L.Parent = this;
        L.Text = "XXX";

        Label M;            
        M = new Label();
        M.Parent = this;
        M.Text = "YYY";
    }
}

然后我在页面中插入这个类:

 <local:Ton></local:Ton>

但该控件未显示在页面中。

请问有人知道原因吗?

谢谢。 干杯,

【问题讨论】:

    标签: xamarin


    【解决方案1】:

    您创建了两个标签,但实际上并未将它们添加到视图层次结构中

    public class Ton : ContentView
    {
        public Ton() : base()
        {
            Label L;            
            L = new Label();
            L.Text = "XXX";
    
            Label M;            
            M = new Label();
            M.Text = "YYY";
    
            // because you have multiple elements, they must be contained in a Layout
            var stack = new StackLayout();
    
            stack.Children.Add(L);
            stack.Children.Add(M);
    
            // assign your controls to the View hierarchy
            this.Content = stack;
    
        }
    }
    

    【讨论】:

    • 您可以直接从堆栈继承来减少代码,而不是在内容视图中添加堆栈。
    【解决方案2】:

    视图是一个抽象类,它不能没有子类。它也不知道如何在里面布置它的孩子。您必须从 Layout&lt;View&gt; 或其他现有布局类(如 Grid、StackLayout、RelativeLayout 等)继承您的类。

    基类取决于您需要如何布局您的孩子。

    请参阅下面的 GitHub 存储库以了解如何创建自定义控件。 https://github.com/harikrishnann/BusyButton-XamarinForms

    【讨论】:

      猜你喜欢
      • 2014-03-08
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2016-04-14
      • 2023-04-03
      • 2012-02-09
      相关资源
      最近更新 更多