A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
Hello,
After testing, you can create and register a ShellItem only from the cs code with the following steps.
Step 1. Create AppShell without item in xaml.
<Shell
x:Class="MauiApp9.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp9"
Shell.FlyoutBehavior="Flyout"
Title="MauiApp9">
</Shell>
Step 2. Create a ShellItem via a static method.
public static class FlyoutHelper
{
public static void GeetDefaultMenuItems()
{
var defaultItems = new List<ShellContent> {
new() { Title="MainPage", ContentTemplate = new DataTemplate(typeof(MainPage)),
Route = nameof(MainPage), FlyoutItemIsVisible = true },
new() { Title="Page1", ContentTemplate = new DataTemplate(typeof(NewPage1)),
Route = nameof(NewPage1), FlyoutItemIsVisible = true },
new() { Title="Page2", ContentTemplate = new DataTemplate(typeof(NewPage2)),
Route = nameof(NewPage2), FlyoutItemIsVisible = true },
};
if(Shell.Current != null )
{
Shell.Current.Items.Clear();
foreach (var item in defaultItems)
{
Shell.Current.Items.Add(item);
}
}
}
}
Step 3. Call the method implemented in the second step in the shell's OnAppearing method.
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
FlyoutHelper.GeetDefaultMenuItems();
}
}
In addition, if you want to call the OnAppearing method from a ViewModel, you need to use the EventToCommand feature provided by the CommunityToolkit.
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.