如何在XAML中填充ContextMenuStrip?

How to fill ContextMenuStrip in XAML?

我已经使用 NotifyIcon 创建了 WPF 应用程序以在托盘中工作。

public partial class MainWindow : Window
{
    public NotifyIcon NotifyIcon { get; } = new NotifyIcon
    {
        Icon = Properties.Resources.status_on_ico,
        Visible = true
    };

    public MainWindow()
    {
        InitializeComponent();

        NotifyIcon.ContextMenuStrip = MyContextMenuStrip;
        NotifyIcon.Click += NotifyIcon_Click;
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
        WindowState = WindowState.Minimized;
    }

    private void NotifyIcon_Click(object sender, EventArgs e)
    {
        Show();
    }
}

XAML of main window 没什么特别的,也不相关。

我想在 XAML 中创建 NotifyIconContextMenuStrip(我知道如何在后面编写代码,但不想这样做)。

这是我所管理的。

<WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>
            <!-- How to add items here? -->
        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>

问题是如何使用 XAML 中的 NameClick 事件处理程序向 ContextMenuStrip.Items 添加项目?

The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?

试试这个:

<WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>
            <wf:ToolStripMenuItem Text="test1" Click="It_Click" />
            <wf:ToolStripMenuItem Text="test2" />
        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>

private void It_Click(object sender, EventArgs e)
{
    MessageBox.Show("click!");
}