首页 > 解决方案 > WindowsFormsHost 托管的 DataVizualization.Chart 中的 ContextMenu

问题描述

我有一个带有使用 System.Windows.Forms.DataVisualization 的图表的 C# WPF 应用程序。我有图表工作。它嵌入在 XAML 中的 WindowsFormsHost 中。我想在图表中添加一个 ContextMenu 以保存图像、更改图表缩放等。但是,我无法显示上下文菜单。主窗口使用 GRID,如果我将上下文菜单添加到网格,则上下文菜单会出现在顶级菜单和状态栏上,但不会出现在图表上。由于图表占据了大部分窗口表面,因此最好将其显示在图表上。

这是一个简化的 XAML,只有一个菜单项:

        <WindowsFormsHost HorizontalAlignment="Stretch" Grid.Row="1" x:Name="wfh" SizeChanged="OnWindowSizeChanged" MouseDown="OnWindowsFormsHostMouseDown" Background="Transparent">
            <WindowsFormsHost.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save Image" IsEnabled="true" Click="OnClickedSaveImage" ToolTip="Save an image of the chart"/>
                </ContextMenu>
            </WindowsFormsHost.ContextMenu>
            <WindowsFormsHost.Child>
                <mschart:Chart x:Name="nativechart"/>
            </WindowsFormsHost.Child>
        </WindowsFormsHost>

在我后面的代码中:

        private void OnWindowsFormsHostMouseDown(object sender, MouseButtonEventArgs e)
        {
            this.wfh.ContextMenu.IsOpen = true;
        }

我使用了各种不同的选项来设置透明背景,将图表元素放在 WindowsFormsHost.Child 元素中,如图所示,或者直接放在 WindowsFormsHost 中。我无法让 ContextMenu 出现在图表上。有任何想法吗?

标签: c#wpfcontextmenu

解决方案


尝试处理MouseClickWinForms 控件的事件:

<mschart:Chart x:Name="nativechart" MouseClick="nativechart_MouseClick"/>

private void nativechart_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
        this.wfh.ContextMenu.IsOpen = true;
}

推荐阅读