WPF Context menu on left click

2019-01-09 03:01发布

I have a WPF application..In which I have an Image control in Xaml file.

On right click of this image I have a context menu.

I would like to have same to be displayed on "Left click" also.

How do I do this in MVVM way ?

8条回答
小情绪 Triste *
2楼-- · 2019-01-09 03:47

Hey I came across the same problem looking for a solution which I didn't find here.

I don't know anything about MVVM so it's probably not MVVM conform but it worked for me.

Step 1: Give your context menu a name.

<Button.ContextMenu>
    <ContextMenu Name="cmTabs"/>
</Button.ContextMenu>

Step 2: Double click the control object and insert this code. Order matters!

Private Sub Button_Click_1(sender As Object, e As Windows.RoutedEventArgs)
        cmTabs.StaysOpen = True
        cmTabs.IsOpen = True
    End Sub

Step 3: Enjoy

This will react for left & right click. It's a button with a ImageBrush with a ControlTemplate.

查看更多
够拽才男人
3楼-- · 2019-01-09 03:57

You can do this by using the MouseDown event of an Image like this

<Image ... MouseDown="Image_MouseDown">
    <Image.ContextMenu>
        <ContextMenu>
            <MenuItem .../>
            <MenuItem .../>
        </ContextMenu>
    </Image.ContextMenu>
</Image>

And then show the ContextMenu in the EventHandler in code behind

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left)
    {
        Image image = sender as Image;
        ContextMenu contextMenu = image.ContextMenu;
        contextMenu.PlacementTarget = image;
        contextMenu.IsOpen = true;
    }
}
查看更多
登录 后发表回答