Reputation: 2424
The following class derives from System.Windows.Controls.UserControl
. In said class I call OpenFileDialog
to open a XAML file (workflow file). Next, I implement a dynamic menu when right clicking the mouse. The menu does not show up. Is this a threading problem or a UI problem? In my research I've been unable to discover a solution.
Thanks in advance.
private void File_Open_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog();
fileDialog.Title = "Open Workflow";
fileDialog.Filter = "Workflow| *.xaml";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
LoadWorkflow(fileDialog.FileName);
MouseDown += new System.Windows.Input.MouseButtonEventHandler(mouseClickedResponse);
}
}
private void mouseClickedResponse(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
LoadMenuItems();
}
}
private void LoadMenuItems()
{
System.Windows.Controls.ContextMenu contextmenu = new System.Windows.Controls.ContextMenu();
System.Windows.Controls.MenuItem item1 = new System.Windows.Controls.MenuItem();
item1.Header = "A new Test";
contextmenu.Items.Add(item1);
this.ContextMenu = contextmenu;
this.ContextMenu.Visibility = Visibility.Visible;
}
Upvotes: 2
Views: 13031
Reputation: 71
Came across this problem myself, I used this:
ContextMenu.IsOpen = true;
MSDN Documentation on ContextMenu
Upvotes: 7
Reputation: 609
you have to call the ContextMenu's Show(Control, Point) method. furthermore i wouldn't instantiate a new context menu each time the control is clicked, instead i would do something like that:
MyClass()
{
// create the context menu in the constructor:
this.ContextMenu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem item1 = new System.Windows.Forms.MenuItem();
item1.Text = "A new Test";
this.ContextMenu.Items.Add(item1);
}
private void mouseClickedResponse(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
// show the context menu as soon as the right mouse button is pressed
this.ContextMenu.Show(this, e.Location);
}
}
Upvotes: 0