I'm working on an application that runs on two monitors. I have two screens defined in Windows. In my WPF app, I have one window opening on Screen1 and a second window opening on Screen2. This second window has images each with a ContextMenu. On the click event of the image I call the method EnableLeftClick.
For some strange reason, the context menu appears in a random location on the first screen. I call this method because I needed to enable the context menu to open on the left mouse click. I tried using PlacementTarget, I tried using the ContextMenuService, but nothing is working. How can I force the ContextMenu to open exactly where the mouse is clicked? I tried setting the PlacementMode to Mouse and MousePoint, but always getting the same results. It appears on the other screen.
private void EnableLeftClick(object sender)
{
var fe = sender as FrameworkElement;
if (fe != null)
{
if (fe.ContextMenu == null) return;
//fe.ContextMenu.PlacementTarget = fe;
//fe.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
//fe.ContextMenu.HorizontalOffset = 0;
//fe.ContextMenu.VerticalOffset = 0;
System.Windows.Controls.ContextMenuService.SetPlacement(fe, System.Windows.Controls.Primitives.PlacementMode.Bottom);
fe.ContextMenu.IsEnabled = true;
fe.ContextMenu.IsOpen = true;
fe.ContextMenu.Visibility = Visibility.Visible;
}
}
What's worse is that the ContextMenu does not even close when I click elsewhere on the screen.
The ContextMenu is initialized in this method that executes when the Window opens. I Basically attach a different ContextMenu on several images.
public void DoDynamicMenus()
{
m_menuService = GcsIocContainer.Instance.Container.Resolve<IMenuIntegrationService>();
foreach (var menuConfiguration in m_menuService.GetMenuConfigurations())
{
foreach (var image in GetImageComponents<IAlsGraphic>(m_components))
{
if (menuConfiguration.RootImageName.Equals(image.Name, StringComparison.InvariantCultureIgnoreCase))
{
var contextMenu = new System.Windows.Controls.ContextMenu();
var fe = image.NativeObject as FrameworkElement;
foreach (var mi in menuConfiguration.GetRootMenuItems())
{
var menuItem = new System.Windows.Controls.MenuItem() { Header = mi.ItemCaption };
menuItem.Click += MenuItem_Click;
contextMenu.Items.Add(menuItem);
menuItem.Tag = mi;
}
fe.ContextMenu = contextMenu;
//fe.ContextMenu.Visibility = Visibility.Visible;
fe.Visibility = Visibility.Visible;
contextMenu.IsEnabled = true;
contextMenu.IsOpen = true;
}
}
}
}