显示 Markdown 内容

上一篇命令结果

到目前为止,我们只演示如何在 ListPage 中显示命令列表。 但是,还可以在扩展中显示丰富的内容,例如 markdown。 这可用于显示文档或文档预览。

使用 markdown 内容

IContentPage (及其工具包实现 ContentPage)是用于在命令面板中显示所有类型的丰富内容的基础。 若要显示 Markdown 内容,可以使用 MarkdownContent 类。

作为一个简单的示例,我们可以创建以下页面:

注释

如果从前面的部分进行操作,请将以下代码从 MarkdownPage 修改为 <ExtensionName>Page

public class MarkdownPage : ContentPage
{
    public MarkdownPage()
    {
        Icon = IconHelpers.FromRelativePath("Assets\\StoreLogo.png");
        Title = "Markdown page";
    }

    public override IContent[] GetContent()
    {
        return [
            new MarkdownContent("# Hello, world!\n This is a **markdown** page."),
        ];
    }
}

在这个示例中,创建了一个新的 MarkdownPage,用于显示简单的 markdown 字符串。 MarkdownContent 类接收一段 markdown 内容的字符串,并将其呈现在命令面板中。

还可以向页面添加多个内容块。 例如,可以添加两个 markdown 内容块:

public override IContent[] GetContent()
{
    return [
        new MarkdownContent("# Hello, world!\n This is a **markdown** page."),
        new MarkdownContent("## Second block\n This is another block of content."),
    ];
}

这样,就可以在单个页面上混合和匹配不同类型的内容。

添加命令

还可以将命令添加到 ContentPage。 这样,你可以在内容上下文中添加用户调用的其他命令。 例如,如果你有一个显示文档的页面,则可以添加一个命令以在文件资源管理器中打开文档:


public class MarkdownExamplePage : ContentPage
{
    public MarkdownExamplePage()
    {
        Icon = new("\uE8A5"); // Document icon
        Title = "Markdown page";
        Name = "Preview file";

        Commands = [
            new CommandContextItem(new OpenUrlCommand("C:\\Path\\to\\file.txt")) { Title = "Open in File Explorer" },
        ];
    }
    public override IContent[] GetContent()
    {
        return [
            new MarkdownContent("# Hello, world!\n This is a **markdown** document.\nI live at `C:\\Path\\to\\file.txt`"),
        ];
    }
}

下一步: 使用表单获取用户输入