【MAUI】 Shell Tab自定义拓展

概述

这篇文章就是想要拓展下Shell中的Tab。

目前我还没有找到可以动态生成Tab的方法,所以我只能自己写一个,可能不够好,但或许是个思路。

代码:https://github.com/simphonydeveloper/MauiShellTabExample/

正文

效果如图,PageA-PageE都是公用一个ContentPage,并且由数据源绑定。

 

 

 因为Shell的Tab没有类似ItemSource的属性,所以我的想法是拓展Tab,写一个ItemSource.

CustomShellTab

/// <summary>
/// Custom Shelltab
/// <see cref="Tab"/>
/// </summary>
public class CustomShellTab : Tab
{


    public static BindableProperty ItemSourceProperty =
        BindableProperty.Create(
            nameof(ItemSource),
            typeof(IEnumerable),
            typeof(CustomShellTab),
            defaultValue: _ = Array.Empty<object>(),
            propertyChanged: ItemSourceChanged);
    public CustomShellTab()
    {

    }


    public IEnumerable ItemSource
    {
        get
        {
            return (IEnumerable)GetValue(ItemSourceProperty);
        }
        set
        {
            SetValue(ItemSourceProperty, value);
        }
    }


    /// <summary>
    /// set shellcontent to items
    /// </summary>
    public void UpdateItemSource()
    {

        foreach (string item in ItemSource)
        {
            var datatemplate = new DataTemplate(typeof(PageA));
            this.Items.Add(new ShellContent { ContentTemplate = datatemplate, Title = item });
        }
    }
    static void ItemSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var tab = bindable as CustomShellTab;

        if (tab == null)
            return;

        if (newValue == null)
            return;

        tab.UpdateItemSource();

    }
}

这样能够在绑定数据源之后,根据数据源生成页面。

页面

这里有一个问题,我始终无法获取Title值,如果有知道问题的大佬可以留言。

public class PageA : ContentPage
{


    public PageA()
    {
        InitPage();
    }

    void InitPage()
    {
        Console.WriteLine(this.Title);
        Content = new VerticalStackLayout
        {
            Children = {
                new Label { HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, Text =this.Title
                }
            }
        };

    }
}

数据

    /// <summary>
    /// Analog data source
    /// </summary>
    public class PageInstance
    {
        public static List<string> Pages = new List<string> { "PageA", "PageB", "PageC", "PageD", "PageE" };
    }

Shell

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
    x:Class="MauiShellTabExample.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MauiShellTabExample"
    Shell.FlyoutBehavior="Disabled">

    <TabBar>
        <local:CustomShellTab ItemSource="{x:Static local:PageInstance.Pages}" x:DataType="local:PageInstance">
            
        </local:CustomShellTab>
    </TabBar>

</Shell>

 

posted @ 2023-03-03 16:02  飞天猪皮怪  阅读(317)  评论(0编辑  收藏  举报