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

时间:2016-11-22 18:32:54

标签: xamarin.forms cross-platform

我是初学者并且正在学习如何在Visual Studio 2015中以xamarin形式开发跨平台应用程序。我有一个 stackLayout ,其中包含Label和按钮“OK”等元素。我想在点击OK“按钮”(动态添加控件)后在“确定”按钮下添加一个新标签。 但是当我这样做时,新按钮添加标签,但现有控件(标签和按钮)消失到某个地方。我错了吗?。请帮我解决这个问题。[附图显示我的输出] [1]

图片:[1]:https://i.stack.imgur.com/YLlQN.jpg

以下是我的应用程序的代码。

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>

由于

1 个答案:

答案 0 :(得分:2)

ContentPage只有一个Content元素。此代码创建一个新的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声明中)

var label = new Label { Text = "This is a new label.", TextColor = Color.FromHex("#77d065"), FontSize = 30, TranslationY = 30 };
layout.Children.Add(label);