繁体   English   中英

动态将XAML与后台代码耦合

[英]Dynamically coupling XAML with code-behind

一点背景资料

我正在学习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页面和类背后的代码在xaml文件中与x:Class定义紧密耦合。 Xaml页面不能被继承,但是ContentPage类可以,但是我看不到能解决您的问题。 如果只需要一个xaml页面,则必须在后面的代码中创建渲染逻辑,例如

public HomePage(string title)
{
    InitializeComponent();

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

然后,您的VM可以包含页面特定的数据。 此概念使用MVVM ,在使用Xamarin Forms时强烈建议使用。

还可以看一下用于渲染通用页面部分的ControlTemplate

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM