.NET 毛伊岛 : Customize Shell TitleView and bind to current page title

标签 .net maui .net-maui.shell

我想用我自己的自定义布局替换默认的 Shell header ,如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
    x:Class="MyNamespace.App.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MyNamespace.App"
    xmlns:pages="clr-namespace:MyNamespace.App.Pages"
    BindingContext="{x:Static local:MainView.Instance}"
    Shell.FlyoutBehavior="{Binding ShellFlyoutType}"
    x:Name="shellMain">

    <Shell.TitleView>
        <Grid ColumnDefinitions="*,200">
            <Label BindingContext="{x:Reference shellMain}" Text="{Binding Path=CurrentPage.Title, Mode=OneWay}" FontSize="Large" TextColor="White" />
            <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" />
        </Grid>
    </Shell.TitleView>
    
    
    <ShellContent
        Title=" Login"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="login" FlyoutItemIsVisible="False" />

    
    <ShellContent Title="Dashboard" 
                      ContentTemplate="{DataTemplate pages:DashboardPage}"
                      Route="dashboard" />
</Shell>

我无法绑定(bind)当前页面标题。 我的 AppShell.xaml Shell 声明如下 <Shell ... x:Name="shellMain">

最佳答案

作为替代方案,您可以在 OnNaviged 方法中设置标题 View :

在 AppShell.xaml 中,定义标签的名称

<Shell.TitleView>
    <Grid ColumnDefinitions="*,200">
        <Label BindingContext="{x:Reference shellMain}" x:Name="mylabel" FontSize="Large" TextColor="White" />
        <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" />
    </Grid>
</Shell.TitleView>

在AppShell.xaml.cs中,重写OnNaviged方法,获取当前项目

protected override void OnNavigated(ShellNavigatedEventArgs args)
{
    base.OnNavigated(args);

    var shellItem = Shell.Current?.CurrentItem;
    string title = shellItem?.Title;
    int iterationCount = 0;
    while (shellItem != null
        && title == null)
    {
        title = shellItem.Title;
        shellItem = shellItem.CurrentItem;

        if (iterationCount > 10)
            break;  // max nesting reached

        iterationCount++;
    }

    myLabel.Text = title;
}

希望它对您有用。

关于.NET 毛伊岛 : Customize Shell TitleView and bind to current page title,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75257860/

相关文章:

.net - 如何在ASP.NET MVC中更改默认 View 位置方案?

.net - .NET 世界中的前端开发人员 - 我需要知道什么?

C# WinForm + Barcode Scanner 输入,TextChanged 错误

c# - Entity Framework 自跟踪实体和 ASP MVC .NET 和托管扩展框架的问题

maui - .NET MAUI 边框和框架之间的区别

maui - 在 .NET MAUI 中围绕用户头像创建圆形边框

mvvm - 如何根据.net maui 中的条件进行绑定(bind)?

maui - .Net Maui - ShellContent 导航问题