Xamarin 表单:如何动态地(在应用程序中)从 CRUD 函数添加菜单项?

Xamarin forms: How to Dynamically (in the app) add menu items from a CRUD function?

我有一个完美运行的 CRUD 功能,我需要做的是使用 CRUD 功能启用添加菜单项。

使用CRUD创建的新项目应该显示在这里:Image example

我试图在以下问题中找到解决方案:,以及许多其他问题。但是这些文章没有回答我的问题。

如前所述,我理解您的逻辑,但我无法将其应用到我的项目中。而且我在这方面还很陌生,所以我将分享一些代码,希望有人能提供帮助。

这是我的AppShell.xaml

    <?xml version="1.0" encoding="UTF-8"?>
 <Shell xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:MyTestApplication.Views"
        xmlns:viewModels="clr-namespace:MyTestApplication.ViewModels;assembly=MyTestApplication"
        Title="MyTestApplication"
        x:Class="MyTestApplication.AppShell">
        
     <Shell.Resources>
         <ResourceDictionary>
             <Style x:Key="BaseStyle" TargetType="Element">
                 <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                 <Setter Property="Shell.ForegroundColor" Value="White" />
                 <Setter Property="Shell.TitleColor" Value="White" />
                 <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                 <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
                 <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
                 <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
                 <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
                 <Setter Property="Shell.TabBarTitleColor" Value="White"/>
             </Style>
             <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
             <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />
    
             <Style Class="MenuItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                 <Setter Property="VisualStateManager.VisualStateGroups">
                     <VisualStateGroupList>
                         <VisualStateGroup x:Name="CommonStates">
                             <VisualState x:Name="Normal">
                                 <VisualState.Setters>
                                     <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                 </VisualState.Setters>
                             </VisualState>
                         </VisualStateGroup>
                     </VisualStateGroupList>
                 </Setter>
             </Style>
         </ResourceDictionary>
     </Shell.Resources>
      
    
     <FlyoutItem Title="Home" Icon="home.png">
             <ShellContent Route="MainPage" ContentTemplate="{DataTemplate local:MainPage}" />
         </FlyoutItem>
         <FlyoutItem Title="Settings" Icon="setting.png">
             <ShellContent Route="SettingsPage" ContentTemplate="{DataTemplate local:SettingsPage}" />
         </FlyoutItem>
    
     <MenuItem Icon="logout.png" Text="Logout" StyleClass="MenuItemLayoutStyle" Clicked="OnMenuItemClicked">
     </MenuItem>
    
     <TabBar >
         <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
     </TabBar>
    
 </Shell>

这是我的AppShell.xaml.cs

public partial class AppShell : Xamarin.Forms.Shell
{
public List<ElseMenuItem> FlyoutItems { get; set; } = new List<ElseMenuItem>();

public AppShell()
     {
         InitializeComponent();
     }
     private async void OnMenuItemClicked(object sender, EventArgs e)
     {
         await Shell.Current.GoToAsync("//LoginPage");
     }
 }

这是我的 AddUrl.xaml.cs(我想在菜单中添加的项目是“URL 按钮”,所以当我点击时,它会带我去一个特定的网页。这就是为什么我称它为 ADDURL)

[XamlCompilation(XamlCompilationOptions.Compile)]
     public partial class AddUrl : ContentPage
     {
         private DbService _services;
         bool _isUpdate;
         int urlId;
         public AddUrl()
         {
             InitializeComponent();
             _services = new DbService(); // Initializing db service
             _isUpdate = false; // Boolean logic, if constructor calls without any Url parameters it is going to add new record
         }
    
         public AddUrl(Urls obj)
         {
             //If constructor calls parameter of Url object, it is going to update the record
             InitializeComponent();
             _services = new DbService();
             if (obj != null)
             {
                 urlId = obj.Id;
                 TxtUrlName.Text = obj.Name;
                 TxtUrl.Text = obj.Url;
    
    
                 _isUpdate = true;
             }
         }
         private async void btnSaveUpdate_Clicked(object sender, EventArgs e)
         {
             Urls obj = new Urls(); // Use of url object
    
             //Text box value
             obj.Name = TxtUrlName.Text;
             obj.Url = TxtUrl.Text;
    
             // If _isUpdate is true, call UpdateUrls method
             if (_isUpdate)
             {
                 obj.Id = urlId;
                 await _services.UpdateUrls(obj);
             }
             // Else insert record
             else
             {
                 _services.InsertUrls(obj);
             }
             await this.Navigation.PopModalAsync();
         }
    
    
     }

这是AddUrl.xaml

  <ContentPage.Content>
         <StackLayout Margin="10" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
             <Entry x:Name="TxtUrlName" Placeholder="Enter Url Name" />
             <Entry x:Name="TxtUrl" Placeholder="Enter Url" />
             <Button x:Name="btnSaveUpdate" Text="Save" Clicked="btnSaveUpdate_Clicked" />
         </StackLayout>
     </ContentPage.Content>

最后我有一个 SettingsPage.cs,我可以在其中显示和添加函数 url。

[XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class SettingsPage : ContentPage
     {
      public Settings Settings { get; set; }
         DbService  services;
         public SettingsPage ()
  {
  InitializeComponent();
             // Creates the Settings Model
      Settings = new Settings();
             // Sets the Settings Model as the BindingContext for "filling" the SettingsPage with the current AppSettings.
      BindingContext = Settings;
             services = new DbService();
    
         }
    
         protected async override void OnAppearing()
         {
             showUrl(); // Returns GetAllUrls
             base.OnAppearing();
         }
    
         private void showUrl()
         {
             var res = services.GetAllUrls();
             lstUrls.ItemsSource = res; // Binding with listview
         }
    
    
         //This method is used to insert data into db 
         private async void BtnAddRecord_Clicked(object sender, EventArgs e)
         {
             await this.Navigation.PushModalAsync(new AddUrl(), true);
    
         }
    
          
    
         // Display alert for update and delete
         private async void lstData_ItemSelected(object sender, SelectedItemChangedEventArgs e)
         {
             if (e.SelectedItem != null)
             {
                 Urls obj = (Urls) e.SelectedItem;
                 string res = await DisplayActionSheet("Operation", "Cancel", null, "Update", "Delete");
    
                 switch (res)
                 {
                     case "Update":
                         await this.Navigation.PushModalAsync(new AddUrl(obj), true);
                         break;
                     case "Delete":
                         services.DeleteUrl(obj);
                         showUrl();
                         break;
                            
                 }
                  
                 lstUrls.SelectedItem = null;
             }
    
         }
     }

再次:我不知道如何在我的代码中实现逻辑。我有一个完美运行的 CRUD 函数,但我需要使用它在菜单中动态添加项目。希望有人能给我指路。

谢谢!

关于您的CRUD操作,您可以在操作数据库之前调用Items.Add()方法和Items.Remove()方法。

喜欢在 AddUrl.xaml.cs 中添加菜单项:

private async void btnSaveUpdate_Clicked(object sender, EventArgs e)
     {
         Urls obj = new Urls(); // Use of url object

         //Text box value
         obj.Name = TxtUrlName.Text;
         obj.Url = TxtUrl.Text;

         // If _isUpdate is true, call UpdateUrls method
         if (_isUpdate)
         {
             obj.Id = urlId;
             await _services.UpdateUrls(obj);
         }
         // Else insert record
         else
         {
             _services.InsertUrls(obj);
         }
         AppShell.Current.Items.Add(your menuitem);//add the menuitems
         await this.Navigation.PopModalAsync();
     }

删除 SettingsPage.cs 中的菜单项:

private async void lstData_ItemSelected(object sender, SelectedItemChangedEventArgs e)
     {
         if (e.SelectedItem != null)
         {
             Urls obj = (Urls) e.SelectedItem;
             string res = await DisplayActionSheet("Operation", "Cancel", null, "Update", "Delete");

             switch (res)
             {
                 case "Update":
                     await this.Navigation.PushModalAsync(new AddUrl(obj), true);
                     break;
                 case "Delete":
                     services.DeleteUrl(obj);
                     AppShell.Current.Items.Remove(your menuitem); //remove
                     showUrl();
                     break;
                        
             }
              
             lstUrls.SelectedItem = null;
         }

     }