在Xamarin.Forms中,页面之间传递数据是一个常见的需求。传递整数(Int)也不例外。以下是一些基础概念和相关方法:
Navigation.PushAsync
方法的参数传递数据。// 在源页面
public class SourcePage : ContentPage
{
public SourcePage()
{
Button button = new Button { Text = "Go to Target Page" };
button.Clicked += async (sender, e) =>
{
await Navigation.PushAsync(new TargetPage(42));
};
Content = new StackLayout
{
Children = { button }
};
}
}
// 在目标页面
public class TargetPage : ContentPage
{
public int PassedInt { get; }
public TargetPage(int passedInt)
{
PassedInt = passedInt;
Label label = new Label { Text = $"Passed Int: {PassedInt}" };
Content = new StackLayout
{
Children = { label }
};
}
}
// 在源页面
public class SourcePage : ContentPage
{
public SourcePage()
{
Button button = new Button { Text = "Go to Target Page" };
button.Clicked += async (sender, e) =>
{
var navigationParams = new NavigationParameters();
navigationParams.Add("passedInt", 42);
await Navigation.PushAsync(new TargetPage(), navigationParams);
};
Content = new StackLayout
{
Children = { button }
};
}
}
// 在目标页面
public class TargetPage : ContentPage
{
public TargetPage()
{
NavigationPage.SetHasNavigationBar(this, false);
var passedInt = NavigationContext.Current.Parameters.GetValue<int>("passedInt");
Label label = new Label { Text = $"Passed Int: {passedInt}" };
Content = new StackLayout
{
Children = { label }
};
}
}
原因:可能是由于导航参数未正确设置或获取,或者构造函数参数未正确传递。 解决方法:
通过以上方法,可以在Xamarin.Forms中有效地在不同页面之间传递整数数据。
领取专属 10元无门槛券
手把手带您无忧上云