在xamarin.forms中动态添加新控件时,现有控件将消失

在xamarin.forms中动态添加新控件时,现有控件将消失,xamarin.forms,cross-platform,Xamarin.forms,Cross Platform,我是一名初学者,正在学习在visual Studio 2015中使用xamarin表单开发跨平台应用程序。我有一个堆栈布局,其中包含标签和按钮“OK”等元素。我想在单击OK“button”(动态添加控件)时,在“OK”按钮下方添加一个新标签。 但是当我这样做时,新按钮添加了标签,但是现有控件(标签和按钮)消失了。我有什么地方出错了吗?请帮我解决这个问题。[附图显示了我的输出][1] 图片:[1]: 下面是我的应用程序的代码 using System; using System.Collectio

我是一名初学者,正在学习在visual Studio 2015中使用xamarin表单开发跨平台应用程序。我有一个堆栈布局,其中包含标签和按钮“OK”等元素。我想在单击OK“button”(动态添加控件)时,在“OK”按钮下方添加一个新标签。 但是当我这样做时,新按钮添加了标签,但是现有控件(标签和按钮)消失了。我有什么地方出错了吗?请帮我解决这个问题。[附图显示了我的输出][1]

图片:[1]:

下面是我的应用程序的代码

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代码:

<?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>


谢谢,ContentPage只有一个内容元素。这段代码创建一个新的StackLayout,并用新内容替换现有内容(在XAML中定义)

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);
向现有布局中添加其他内容(需要将
x:Name=“layout”
添加到XAML StackLayout声明中)


谢谢你,先生。你的建议对我很有效。我还想知道我是否可以将导航页面和选项卡页面放在一起?。我有三个xaml页面,分别是A.xaml、B.xaml、C.xaml。通过将代码编写为MainPage=newnavigationpage(newa()),我创建了一个as导航页面;在App.cs中。现在我希望B和C是tabbedpage。因此,我想通过单击页面a中的按钮导航到选项卡页面B和C。我如何实现这一点?
var label = new Label { Text = "This is a new label.", TextColor = Color.FromHex("#77d065"), FontSize = 30, TranslationY = 30 };
layout.Children.Add(label);