如何在XAML中填写ContextMenuStrip?

时间:2017-06-06 12:49:52

标签: c# wpf winforms xaml winforms-interop

我已使用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没什么特别且不相关。

我想在XAML中创建ContextMenuStrip NotifyIcon(我知道如何编写代码,但不想要它)。

以下是我所管理的内容。

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

问题是如何在XAML中使用ContextMenuStrip.ItemsName事件处理程序向Click添加项目?

1 个答案:

答案 0 :(得分:2)

  

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

试试这个:

<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!");
}