在父按钮上添加子按钮单击Xamarin.forms
本文关键字:按钮 单击 Xamarin forms 添加 | 更新日期: 2023-09-27 18:14:38
我一直在尝试在Android的按钮点击上添加一个标签视图到Stacklayout。但是它抛出空指针异常。下面是我想要达到的目标。谁能告诉我如何在xamarin.forms
中实现这一点?Xamarin的。c#中的窗体代码
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 );
}
Thanks in Advance
你的代码是这样工作的…一个微小的变化-使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 ();
}
}