c# - 在按钮上向父项添加子项单击 Xamarin.forms

标签 c# android xamarin xamarin.forms

我一直在尝试在 Android 中单击按钮时向 Stacklayout 添加标签 View 。 但它抛出空指针异常。以下是我想要实现的目标。谁能就如何在 xamarin.forms 中实现这一点提出建议

C# 中的 Xamarin.Forms 代码

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

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

提前致谢

最佳答案

您的代码按原样工作...只需一点小改动 - 将 parent 设为类字段,以便从 OnButtonClicked

中引用它

确保更新解决方案包,以便拥有最新的 Xamarin.Forms。始终在解决方案级别更新包,以免发生版本冲突

此版本已经过测试并可在 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 ();
        }
    }

关于c# - 在按钮上向父项添加子项单击 Xamarin.forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24929977/

相关文章:

android - 我如何确保我的应用支持最低的 Google Play Services 4.1 版本?

xamarin - Xamarin Forms 中的 Android 占位符\提示文本

c# - 迁移到异步 : Repository

c# - 在哪里存储程序集的最佳实践?

c# - 无法加载 PDF 文档(ASP.NET MVC ajax)

Android 动态壁纸 -- OpenGL 与 Canvas

c# - 获取组装所需的组件?

android - 构建完成但应用程序未运行 - android

ios - 如何在 Xamarin.iOS 中识别 iOS 版本

xamarin - DelayBind什么时候用?