I am a beginner and learning to develop cross-platform application in xamarin forms in visual Studio 2015. I have a stackLayout in which elements like Label and button "OK" are present. I want to add a new label below "OK" button on click of OK "button" (Dynamically adding control). But when i do so the new button adds the label but the existing controls(label and button) disappears to somewhere. Am i going wrong somewhere ?.Please help me sort this problem.[The attached image shows my output][1]
Image : [1]: https://i.stack.imgur.com/YLlQN.jpg
This below is the code of my App.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Practise
{
public partial class Page2 : ContentPage
{
public Page2 ()
{enter code here
InitializeComponent ();
}
private void OkButton_Clicked(object sender, EventArgs e)
{
var layout = new StackLayout();
var label = new Label { Text = "This is a new label.", TextColor = Color.FromHex("#77d065"), FontSize = 30, TranslationY = 30 };
this.Content = layout;
layout.Children.Add(label);
}
}
}
Xaml code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Practise.Page2" Title="App1">
<StackLayout>
<Label Text="Click to add new label" HorizontalOptions="Center" TranslationY="45" FontSize="Medium"/>
<Button x:Name="OkButton" Clicked="OkButton_Clicked" Text="Ok" HorizontalOptions="Center" WidthRequest="100" VerticalOptions="Center" HeightRequest="45" TranslationY="60"/>
</StackLayout>
</ContentPage>
Thanks