实际上,有许多不同的解决方案可以实现它。正如@Hobby Dev所说,您可以设置属性IsVisible(也许会使用MVVM)。由于您是 Xamarin 的新手,因此我提供了一种易于理解的解决方案。
在xml中
<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Button Text="Groceries" Clicked="Button_Clicked"/>
</StackLayout>
<StackLayout x:Name="stack1" Grid.Row="1" Orientation="Horizontal" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
</StackLayout>
<StackLayout x:Name="stack2" Grid.Row="2" Orientation="Horizontal" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
</StackLayout>
</Grid>
</StackLayout>
在后面的代码中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;
namespace xxx
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
List<MyButton> myButtons = new List<MyButton>() { new MyButton("Sweet", MyButton_Clicked), new MyButton("Candy", MyButton_Clicked), new MyButton("Gum", MyButton_Clicked) };
stack1.Children.Clear();
foreach(MyButton myButton in myButtons)
{
stack1.Children.Add(myButton);
}
}
private void MyButton_Clicked(object sender, EventArgs e)
{
var mybutton = sender as MyButton;
var title = mybutton.Text;
List<MyButton> myButtons = new List<MyButton>();
if (title=="Sweet")
{
myButtons = new List<MyButton>() { new MyButton("111", MyButton_Clicked), new MyButton("222", MyButton_Clicked), new MyButton("333", MyButton_Clicked) };
}
else if (title== "Candy")
{
myButtons = new List<MyButton>() { new MyButton("444", MyButton_Clicked), new MyButton("555", MyButton_Clicked), new MyButton("666", MyButton_Clicked) };
}
else
{
myButtons = new List<MyButton>() { new MyButton("777", MyButton_Clicked), new MyButton("888", MyButton_Clicked), new MyButton("999", MyButton_Clicked) };
}
stack2.Children.Clear();
foreach (MyButton myButton in myButtons)
{
stack2.Children.Add(myButton);
}
}
}
public class MyButton:Button
{
public MyButton(string title,EventHandler clicked)
{
this.Text = title;
Clicked += clicked;
}
}
}
我使用静态数据只是为了演示,你可以从数据库或webservice中获取数据。