Hi,
today I want to share with you the fast way for creating a dropdown menu on WPF.
You can download sample code here.

The following image display the result (remark that you can customize the Button look&feel as you need):

The idea is to use the WPF ContextMenu modifying the way to open it.
The first step consist in creating a Button with a ContextMenu and disabling the ContextMenuService for this Button object. In this way the right click does not show the ContextMenu. Here the code:

        <Button Content="Click Me" 
                Click="Button_Click"
                ContextMenuService.IsEnabled="False" 
                Margin="42,40,89,72">
            <Button.ContextMenu>
                <ContextMenu >
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                </ContextMenu>
            </Button.ContextMenu>
        </Button>

The second step consist in displaying the ContextMenu when the button is clicked. This is achieved by few lines of code:

        private void Button_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;
        } 

Stay tuned and happy coding 😉
Marzio.

Advertisements