Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Child to the Parent on Button Click Xamarin.forms

I have been trying to add a Label view to the Stacklayout on Button Click in Android. But It throws Null Pointer exception. Below is what I'm trying to acheive. Can anyone please advice on how to acheive this in xamarin.forms

Xamarin.Forms Code in C#

 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 );

Adding Label in 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 ); 
}

Thanks in Advance

like image 965
Femil Shajin Avatar asked Jul 24 '14 09:07

Femil Shajin


1 Answers

Your code works as is... with one tiny change - make parent a class field so it's referenced from within the OnButtonClicked

Make sure you update the solution packages so you have the latest Xamarin.Forms. Always update the packages on the solution level so do don't get versioning conflicts

This version was tested and works on 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 ();
        }
    }
like image 93
Sten Petrov Avatar answered Sep 22 '22 00:09

Sten Petrov