XAML 如何在.NET maui应用程序中为MenuBarItem给予功能?

kq0g1dla  于 2023-04-27  发布在  .NET
关注(0)|答案(1)|浏览(147)

在我的.NET MAUI应用程序中,我创建了一个这样的菜单:

<ContentPage.MenuBarItems>
    <MenuBarItem Text="Passwords">
        <MenuFlyoutItem Text="New"/>
        <MenuFlyoutItem Text="Edit"/>
        <MenuFlyoutItem Text="Delete"/>
        <MenuFlyoutItem Text="Move"/>
    </MenuBarItem>
    <MenuBarItem Text="Groups">
        <MenuFlyoutItem Text="New"/>
        <MenuFlyoutItem Text="Delete"/>
        <MenuFlyoutItem Text="Rename"/>
    </MenuBarItem>
    <MenuBarItem Text="Tools">
        <MenuFlyoutSubItem Text="Password Viewing">
            <MenuFlyoutItem Text="Create Password"/>
            <MenuFlyoutItem Text="Lock Password Viewing"/>
            <MenuFlyoutItem Text="Change Password"/>
        </MenuFlyoutSubItem>
        <MenuFlyoutSubItem Text="Password Database">
            <MenuFlyoutItem Text="Create New Database"/>
            <MenuFlyoutItem Text="Change Current Database"/>
            <MenuFlyoutItem Text="Change Password"/>
        </MenuFlyoutSubItem>
    </MenuBarItem>
    <MenuBarItem Text="Exit" />
</ContentPage.MenuBarItems>

但是现在我想给予MenuBarItem一个点击时的函数。例如,当用户点击退出MenuBarItem时,我如何关闭表单?
我尽力了

<MenuBarItem Text="Exit" Clicked="Exit_click" />

但我一直收到信息
在类型“MenuBarItem”中未找到属性“Clicked”
还有别的办法吗

0g0grzrc

0g0grzrc1#

您可以使用Commands执行此操作,但仅适用于MenuFlyoutItem示例AFAIK:

<ContentPage.MenuBarItems>
    <MenuBarItem Text="Passwords">
        <MenuFlyoutItem
           Text="New"
           Command="{Binding NewPasswordCommmand}" />
        <MenuFlyoutItem Text="Edit"/>
        <MenuFlyoutItem Text="Delete"/>
        <MenuFlyoutItem Text="Move"/>
    </MenuBarItem>
</ContentPage.MenuBarItems>

在你的ViewModel中,你将有各种各样的命令来绑定,例如:

// Creates a Command with the name NewPasswordCommand
[RelayCommand]
private void NewPassword()
{
    //Do something here...
}

如果您不使用MVVM源生成器(c.f. [RelayCommand]),您也可以使用经典的实现:

private ICommand _newPasswordCommand;
public ICommand NewPasswordCommand => _newPasswordCommand ??= new Command(NewPassword);

private void NewPassword()
{
   //Do something here...
}

相关问题