在按钮上向父级添加子级单击Xamarin.forms

Fem*_*jin 5 c# android xamarin xamarin.forms

我一直在尝试在Android上的Button Click上向Stacklayout添加Label视图.但它会抛出空指针异常.以下是我想要实现的目标.任何人都可以请求如何在xamarin.forms中实现这一点

C#中的Xamarin.Forms代码

 StackLayout parent= new StackLayout ();

 Button add= new Button
        {
            HorizontalOptions=LayoutOptions.End,
            BackgroundColor=Xamarin.Forms.Color.White,
            Text="ADD",
            TextColor=Xamarin.Forms.Color.Maroon,
        };

 add.Clicked += OnButtonClicked;

 Label firstLabel = new Label
        {
            Text = "Label 1",
            HorizontalOptions = LayoutOptions.StartAndExpand,
            TextColor=Xamarin.Forms.Color.FromHex("#000000")
        };
 parent.Children.Add(add);
 parent.Children.Add(firstLabel );
Run Code Online (Sandbox Code Playgroud)

在ButtonClick中添加标签

 void OnButtonClicked(object sender, EventArgs e)
 {

   Label secondLabel = new Label
        {
            Text = "Label 1",
            HorizontalOptions = LayoutOptions.StartAndExpand,
            TextColor=Xamarin.Forms.Color.FromHex("#000000")
        };
  parent.Children.Add(secondLabel ); 
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ste*_*rov 7

你的代码按原样运行...... parent只需要做一个微小的改动 - 创建一个类字段,以便从中引用它OnButtonClicked

确保更新解决方案包,以便获得最新的Xamarin.Forms.始终在解决方案级别更新软件包,以免出现版本冲突

此版本已经过测试,适用于iOS:

public class LabelPage: ContentPage
    {
        StackLayout parent = null;

        public LabelPage ()
        {
            parent = new StackLayout ();

            Button add = new Button {
                HorizontalOptions = LayoutOptions.End,
                BackgroundColor = Xamarin.Forms.Color.White,
                Text = "ADD",
                TextColor = Xamarin.Forms.Color.Maroon,
            };

            add.Clicked += OnButtonClicked;

            Label firstLabel = new Label {
                Text = "Label 1",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                TextColor = Xamarin.Forms.Color.FromHex ("#000000")
            };
            parent.Children.Add (add);
            parent.Children.Add (firstLabel); 

            Content = parent;
        }

        void OnButtonClicked (object sender, EventArgs e)
        { 
            Label secondLabel = new Label {
                Text = "Label 1",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                TextColor = Xamarin.Forms.Color.FromHex ("#000000")
            };
            parent.Children.Add (secondLabel); 
            //UpdateChildrenLayout ();
        }
    }
Run Code Online (Sandbox Code Playgroud)