将 XAML 与代码隐藏动态耦合



一点背景信息

我正在学习Xamarin.Forms,目前正在努力将我的ContentPage的XAML与我的代码隐藏动态耦合。显然,我完全不知道Xamarin.Form应该如何编写,所以我希望你能忍受我的轻微困惑。

我正在为Android开发一个移动应用程序,并使用BottomNavigationBarXF将导航栏放在底部,效果很好。目前,我正在使用示例项目进行学习。

实际问题

我已经创建了一系列ContentPage,我想在实例化每个新页面时动态耦合。我的ContentPage有相应的代码隐藏,我没有动过;例如,我有一个名为HomePageContentPage,它有这个代码隐藏:

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 和代码隐藏之间的耦合。但是,我发现这样做相当乏味,可能也没有必要。

有什么建议吗?

谢谢

克里斯

Xaml 页面和类背后的代码在具有x:Class定义的 xaml 文件中紧密耦合。Xaml 页面不能继承,但 ContentPage 类可以,但我看不到可以解决您的问题。如果您只关注一个 xaml 页面,则必须在代码隐藏中创建呈现逻辑,例如

public HomePage(string title)
{
InitializeComponent();
switch(title)
{
// set Binding Context to your VM
... BindingContext = titleBasedVM;
}
}

然后,VM 可以包含特定于页面的数据。此概念使用 MVVM,强烈建议在使用 Xamarin 窗体时执行此操作。

另请查看用于呈现通用页面部分的控件模板。

不应尝试动态生成 xaml,因为它不受支持。

最新更新