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
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 ();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With