Question

I have the following xaml that defines a contextmenu in wpf:

<Grid Name="grid">
    <Button x:Name="settingsButton" DockPanel.Dock="Left" Content="Settings" Click="SettingsButtonClicked">
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Header ="Column Chooser">
                    <MenuItem IsCheckable="true" Header="A" IsChecked="{Binding Path=IsAChoosen}"></MenuItem>
                    <MenuItem IsCheckable="true" Header="B" IsChecked="{Binding Path=IsBChoosen}"></MenuItem>
                    <MenuItem IsCheckable="true" Header="C" IsChecked="{Binding Path=IsCChoosen}"></MenuItem>
                </MenuItem>
            </ContextMenu>
        </Button.ContextMenu>
    </Button>
</Grid>

The binding works fine if I bring up the context menu normally from a right-click.

However I want the contextmenu to show when I left-click the button instead of right-click. So I have the following code to do this:

public partial class SettingsView : UserControl
{
    public SettingsView()
    {
        InitializeComponent();
        settingsButton.MouseRightButtonDown += SettingsButtonOnMouseRightButtonDown;
    }

    private void SettingsButtonOnMouseRightButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
    {
        settingsButton.ContextMenu.Visibility = Visibility.Hidden;
    }

    private void SettingsButtonClicked(object sender, RoutedEventArgs e)
    {
        settingsButton.ContextMenu.Visibility = Visibility.Visible;
        settingsButton.ContextMenu.PlacementTarget = sender as Image;
        settingsButton.ContextMenu.IsOpen = true;
    }
}

When I do this the binding doesnt work. Anyone know why it works with a right-click but not when I force it to a left-click?

Was it helpful?

Solution

Instead of Image set the PlacementTarget To Button

private void SettingsButtonClicked(object sender, RoutedEventArgs e)
{
    settingsButton.ContextMenu.Visibility = Visibility.Visible;
    settingsButton.ContextMenu.PlacementTarget = sender as Button;
    settingsButton.ContextMenu.IsOpen = true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top