问题描述
我要在选择后更改选项卡图标和页面,我有2页,但是我想在选择后更改1个选项卡并更改图标和页面,我该怎么做?
public MainPage()
{
InitializeComponent();
var login = new NavigationPage(new login())
{
Title = "login",Icon = "login.png"
};
var register = new NavigationPage(new register())
{
Title = "register",Icon = "register.png"
};
if(CurrentPage is register)
{
Children.Add(login);
}
else
{
Children.Add(register);
}
this.CurrentPageChanged += (object sender,EventArgs e) =>
{
var i = this.Children.IndexOf(this.CurrentPage);
if (i == 0)
{
login.Title = "login";
login.Icon = "login.png";
}
else
{
register.Title = "register";
register.Icon = "register.png";
}
};
解决方法
您可以创建两个布局,并使用按钮在两个布局之间切换:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
Content = firstlayout();
}
public StackLayout firstlayout() {
StackLayout stacklayout = new StackLayout
{
Margin = new Thickness(20),Children =
{
new Label { Text = "Primary colors" },new BoxView { Color = Color.Red },new BoxView { Color = Color.Yellow },new BoxView { Color = Color.Blue },}
};
Button button = new Button
{
Text = "Click to change content2",VerticalOptions = LayoutOptions.EndAndExpand,HorizontalOptions = LayoutOptions.FillAndExpand,HeightRequest = 60,BackgroundColor = Color.Green,TextColor = Color.White
};
button.Clicked += (sender,args) => this.Content = secondlayout();
stacklayout.Children.Add(button);
return stacklayout;
}
public StackLayout secondlayout()
{
StackLayout stacklayout = new StackLayout
{
Margin = new Thickness(20),Children =
{
new Label { Text = "Secondary colors" },new BoxView { Color = Color.Green },new BoxView { Color = Color.Orange },new BoxView { Color = Color.Purple }
}
};
Button button = new Button
{
Text = "Click to change content1",BackgroundColor= Color.Green,TextColor = Color.White
};
button.Clicked += (sender,args) => this.Content = firstlayout();
stacklayout.Children.Add(button);
return stacklayout;
}
}
结果:
或者您可以将Application.Current.MainPage更改为其他页面:
private void Button_Clicked(object sender,EventArgs e)
{
Application.Current.MainPage = new MainPage();
//Or
Application.Current.MainPage = new LoginPage();
}