MahApps - How to Create Menu Button on the Application Titles Bar

2

I have a user button in my title bar that will allow the user to switch between users or exit the application. How do I create a menu that contains both of these features?

<controls:MetroWindow.RightWindowCommands>
        <controls:WindowCommands>           
            <Button>
                <StackPanel Orientation="Horizontal">
                    <Ellipse Width="30"
                       Height="30"
                       Fill="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}">                        
                    </Ellipse>
                    <TextBlock Margin="4 0 0 0"
                   VerticalAlignment="Center"
                   Text="Jalber" />
                </StackPanel>
            </Button>
        </controls:WindowCommands>
    </controls:MetroWindow.RightWindowCommands>

    
asked by anonymous 12.08.2017 / 19:00

1 answer

0

There is a similar example in the MahApps documentation itself.

XAML

Put the following code inside the Controls:MetroWindow tag in the layout file of your Window :

<Controls:MetroWindow.RightWindowCommands>
    <Controls:WindowCommands>
        <Button Content="usuário" Click="Username_Click" >
            <Button.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trocar usuário" Click="ChangeUser_Click" />
                    <MenuItem Header="Sair"  Click="Exit_Click" />
                </ContextMenu>
            </Button.ContextMenu>
        </Button>
    </Controls:WindowCommands>
</Controls:MetroWindow.RightWindowCommands>

Your layout should look like this:

Codebehind

Inthe.csfileofyourWindow,addthefollowingcode:

privatevoidUsername_Click(objectsender,RoutedEventArgse){varbutton=senderasButton;ContextMenucontextMenu=button.ContextMenu;contextMenu.PlacementTarget=button;contextMenu.IsOpen=true;e.Handled=true;}privatevoidChangeUser_Click(objectsender,RoutedEventArgse){}privatevoidExit_Click(objectsender,RoutedEventArgse){}

TheUsername_ClickmethodwilldisplaythemenupreviouslycreatedinXAMLandtheothertwomethodswillbecalledbyclickingonthe"Switch User" and "Exit" menu item, respectively. Just add the desired code within each method.

Final result

    
14.08.2017 / 17:47