I have a C# WPF application with a chart using System.Windows.Forms.DataVisualization. I have the chart working. It is embedded in a WindowsFormsHost in the XAML. I would like to add a ContextMenu to the chart to save the image, change chart scaling etc. But, I cannot get the context menu to show. The main window is using a GRID and If I add the context menu to the grid, then the context menu appears on the top level menu and the status bar but not on the chart. Since the chart takes up most of the window surface it would be better to show it over the chart.
Here's a simplified XAML with just one menu item:
<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>
In the code behind I have:
private void OnWindowsFormsHostMouseDown(object sender, MouseButtonEventArgs e)
{
this.wfh.ContextMenu.IsOpen = true;
}
I have used a variety of different options setting the Background Transparent, putting the chart element inside a WindowsFormsHost.Child element as shown or directly inside the WindowsFormsHost. I have not been able to make the ContextMenu appear over the chart. Any ideas?
CodePudding user response:
Try to handle the MouseClick
event for the WinForms control:
<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;
}