You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MAUI中修改选中MenuItem的样式

在MAUI AppShell中为选中的MenuItem设置加粗样式

由于MenuItem没有内置的选中状态属性,我们需要手动跟踪选中项并修改其字体样式,具体步骤如下:

1. 跟踪选中的MenuItem

在AppShell.xaml.cs中添加私有字段,记录上一次选中的菜单项:

private MenuItem _lastSelectedMenuItem;

2. 统一处理选中状态更新

添加通用方法,用于重置上一项样式并设置当前项为加粗:

private void UpdateSelectedMenuItem(MenuItem currentItem)
{
    // 恢复上一个选中项的字体样式
    if (_lastSelectedMenuItem != null)
    {
        _lastSelectedMenuItem.FontAttributes = FontAttributes.None;
    }
    
    // 设置当前选中项为加粗
    if (currentItem != null)
    {
        currentItem.FontAttributes = FontAttributes.Bold;
        _lastSelectedMenuItem = currentItem;
    }
}

3. 修改每个MenuItem的Clicked事件

在每个菜单项的点击事件处理方法中,先调用上述更新方法,再执行原有导航逻辑:

private void Home_Clicked(object sender, EventArgs e)
{
    UpdateSelectedMenuItem(sender as MenuItem);
    // 保留你的页面导航代码
    // 例如:await Shell.Current.GoToAsync("//main/home");
}

private void Profile_Clicked(object sender, EventArgs e)
{
    UpdateSelectedMenuItem(sender as MenuItem);
    // 页面导航逻辑
}

// 其他菜单项的Clicked事件同理修改

4. 设置初始选中项(可选)

如果需要默认选中某个菜单项(比如首页),在AppShell构造函数中初始化样式:

public AppShell()
{
    InitializeComponent();
    // 先在XAML中给首页MenuItem添加x:Name="homeMenuItem"
    homeMenuItem.FontAttributes = FontAttributes.Bold;
    _lastSelectedMenuItem = homeMenuItem;
}

对应的XAML修改:

<MenuItem x:Name="homeMenuItem"
          Text="{x:Static resource:Languages.Homepage}"
          IconImageSource="{StaticResource house}"
          Clicked="Home_Clicked"></MenuItem>

内容的提问来源于stack exchange,提问作者Ayesh Nipun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 06:43:11