Tuesday, May 7, 2013

WPF Button Menu

I'm currently working on a WPF application that needed a button that would allow users to click and display menu options.  By default when you've got a menu associated with your button you need to right click on the button to display your menu.

By setting "ContextMenuService.IsEnabled=False" in your button and adding the code below to your button click this should resolve that issue.  In the example below you'll see how to setup your button to display a menu when clicked.  Have Fun ☺
< Button x:Name="btnMenu" Content="Menu" HorizontalAlignment="Left" Height="30" ContextMenuService.IsEnabled="False"  Width="100" Click="btnMenu_Click">
 < Button.ContextMenu>
  < ContextMenu>
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < Separator />
     < MenuItem Header="Second Menu">
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < Separator />
     < MenuItem Header="Third Menu" />
     < / MenuItem>
  < / ContextMenu>
 < / Button.ContextMenu>
< / Button>
private void btnMenu_Click(object sender, RoutedEventArgs e)
  {
    (sender as Button).ContextMenu.IsEnabled = true;
    (sender as Button).ContextMenu.PlacementTarget = (sender as Button);
    (sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
    (sender as Button).ContextMenu.IsOpen = true;
  }

No comments:

Post a Comment