--一个小背景信息
我正在学习Xamarin.Forms,目前正在努力将我的ContentPage的XAML与我的代码背后的动态耦合起来。显然,我完全不知道XAML是如何编写的,所以我希望您能理解我的一点困惑。
我正在为Android开发一个移动应用程序,并使用BottomNavigationBarXF将导航栏放在底部,运行良好。目前,我正在使用示例项目作为我的学习。
实际问题
我已经创建了一系列ContentPage,我想在实例化每个新页面时动态地耦合它们。我的ContentPage有相应的代码--后台,我没有碰过它们;例如,我有一个名为HomePage的ContentPage,它的代码后面有这个代码:
namespace BottomBarXFExample
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : ContentPage
{
public HomePage()
{
InitializeComponent();
}
}
}相应的XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="BottomBarXFExample.HomePage">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
我创建页面的方式如下。
string[] tabTitles = { "Me", "Trends", "Home", "Plan", "About" };
ContentPage[] pages = new ContentPage[tabTitles.Length];
for (int i = 0; i < tabTitles.Length; ++i)
{
ContentPage page = createPage(tabTitles[i]);
bottomBarPage.Children.Add(page);
}createPage方法:
private ContentPage createPage(String title)
{
FileImageSource icon = setIcon(title);
ContentPage page = new ContentPage()
{
Title = title,
Icon = icon,
};
// should something happen here with the XAML?
return page;
}setIcon方法:
private FileImageSource setIcon(String title)
{
FileImageSource icon = (FileImageSource)FileImageSource.FromFile(
string.Format(
"ic_" + title.ToLowerInvariant() + ".png",
title.ToLowerInvariant()
));
return icon;
}使用这种方法,我成功地创建了底部导航栏。但是,使用导航栏导航到每个页面时,视图“显然”为空,因为我没有将ContentPage链接到相应的XAML。这能用代码来完成吗?
如果我选择以“正确”的方式实例化每个ContentPage:
HomePage homePage = new HomePage()
{
Title = "Home",
Icon = homeIcon
};然后将它们添加到导航栏中,如下所示:
bottomBarPage.Children.Add(homePage)我确实获得了XAML和代码隐藏之间的耦合。然而,我觉得这样做是相当乏味的,而且可能也是不必要的。
有什么建议吗?
谢谢,
克里斯
发布于 2018-06-06 16:23:22
Xaml页面和类后面的代码在xaml文件中与x:Class定义紧密耦合。Xaml页面不能继承,但是ContentPage类可以,但我看不出解决问题的方法。如果您只负责一个xaml页面,那么您必须在后面的代码中创建呈现逻辑。
public HomePage(string title)
{
InitializeComponent();
switch(title)
{
// set Binding Context to your VM
... BindingContext = titleBasedVM;
}
}然后,VM可以包含特定于页面的数据。这个概念使用MVVM,这是在使用Xamarin表单时强烈推荐的。
还可以查看ControlTemplate来呈现泛型页面部分。
您不应该尝试动态生成xaml,因为它不受支持。
https://stackoverflow.com/questions/50721976
复制相似问题