简体   繁体   中英

How do I get the selected item from Menu attached to a button

In my .xaml, I had a button and when I left clicked it, a menu will be displayed for selection. Here's my .xaml code:

 <Button x:Name="Btn" Content="Btn" HorizontalAlignment="Left"  VerticalAlignment="Top" 
                 Height="26" Width ="40"  IsEnabled="True" 
                 Click="Btn_Click" ContextMenuService.IsEnabled="False"> 

I disabled the ContextMenuService so that the menu wouldn't be able to display when I right clicked the button.

Below is my code to show the menu after I left clicked the button. The name "Menu" referred to the context menu.

private void Btn_Click(object sender, RoutedEventArgs e)
        {
            ContextMenu contextMenu = this.FindName("Menu") as ContextMenu;
            contextMenu.PlacementTarget = sender as Button;
            contextMenu.IsOpen = true;
        }

Is there any solution for returning the value from a context menu selection based on my situation?

I think what you need is a dropdown button , that is efficient fast and well composed.

You can have it in WPF Extended toolkit and a this Link will guide you there.

or a SplitButton in case you need to have button click as well as menu on it.

It sound like you want to change Modes or Properties in your context menu. Therefore what i would have done is create a UserControl as you button and dropdown context menu, that will know each other. When you change "mode" or something similar in your context menu so youll change it in the UserControl properties so that the button will also know it, and you can populate this for later use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM