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

在.NET 7.0 MAUI中,如何根据笔记内容启用指定FlyoutItem?

实现方案(.NET 7.0 完全支持)

步骤1:给目标FlyoutItem命名

修改你的AppShell.xaml,给禁用的FlyoutItem加上x:Name属性,方便后台代码直接操控它的状态:

<FlyoutItem x:Name="SpeechToTextFlyout" Title="Speech To Text" IsEnabled="False"
           Icon="lock.jfif">
    <Tab>
        <ShellContent ContentTemplate="{DataTemplate views:AllNotesPage}" />
    </Tab>
</FlyoutItem>

步骤2:添加全局检查逻辑

在AppShell.xaml.cs里添加一个方法,用来检查所有笔记中是否包含触发文本"iNotesx":

private bool HasNoteWithTriggerText(string triggerText)
{
    // 替换成你的笔记文件实际存储目录,示例用MAUI标准应用私有数据目录
    string notesDirectory = Path.Combine(FileSystem.AppDataDirectory, "Notes");
    
    if (!Directory.Exists(notesDirectory))
        return false;

    // 遍历所有笔记文件(可根据你的文件格式调整后缀,比如*.txt)
    foreach (var filePath in Directory.GetFiles(notesDirectory, "*.*"))
    {
        try
        {
            string noteContent = File.ReadAllText(filePath);
            if (noteContent.Contains(triggerText, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
        }
        catch { /* 跳过无法读取的损坏文件 */ }
    }
    return false;
}

步骤3:应用启动时初始化状态

在AppShell的构造函数里,启动时就检查一次,设置FlyoutItem的初始状态:

public AppShell()
{
    InitializeComponent();
    // 启动时检查并设置状态
    SpeechToTextFlyout.IsEnabled = HasNoteWithTriggerText("iNotesx");
}

步骤4:保存笔记后更新状态

修改NotePage.xaml.cs里的SaveButton_Clicked方法,在保存笔记后立即检查并更新FlyoutItem的状态:

private async void SaveButton_Clicked(object sender, EventArgs e)
{
    if (BindingContext is Models.Note note)
    {
        File.WriteAllText(note.Filename, TextEditor.Text);
        
        // 保存后检查是否满足启用条件
        UpdateSpeechFlyoutStatus();
    }

    await Shell.Current.GoToAsync("..");
}

private void UpdateSpeechFlyoutStatus()
{
    if (Shell.Current is AppShell appShell)
    {
        bool shouldEnable = appShell.HasNoteWithTriggerText("iNotesx");
        appShell.SpeechToTextFlyout.IsEnabled = shouldEnable;
    }
}

补充说明

  • 如果你希望仅当前打开的笔记包含"iNotesx"就启用,可简化逻辑:直接判断TextEditor.Text.Contains("iNotesx"),无需遍历所有文件。
  • 确保笔记存储目录与你实际的存储路径一致,示例中FileSystem.AppDataDirectory是MAUI获取应用私有数据目录的标准方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:16:01