.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/

相关文章:

c# - 为什么我的 C# 应用程序无法加载我的 C++ dll?

c# - .NET 中的动画效果?

c# - 毛伊岛机器人。设置 MainPage 或覆盖 CreateWindow

c# - 如何将 DatePicker 中的 SelectedDateChanged 事件绑定(bind)到 VM 中的命令

c# - NETSDK1201 : For projects targeting . NET 8.0 及更高版本,默认情况下指定 RuntimeIdentifier 将不再生成自包含应用程序

c# - 如何根据MAUI中的绑定(bind)值显示文本

maui - .Net Maui - ShellContent 导航问题

.net MAUI 无法看到 iOS 方法和属性,因为它的状态为禁用

c# - 页面加载的 PrincipalPermission