在按钮上向父级添加子级单击Xamarin.forms

时间:2014-07-24 09:28:33

标签: c# android xamarin xamarin.forms

我一直在尝试在Android上的Button Click上向Stacklayout添加Label视图。 但它会抛出空指针异常。以下是我试图实现的目标。任何人都可以请求如何在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 ); 
}

先谢谢

1 个答案:

答案 0 :(得分:6)

您的代码按原样运行...只需进行一项微小更改 - 将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 ();
        }
    }