Mahapps - How to create Menu User Button in the Application Title Bar

Asked

Viewed 112 times

2

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

<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>

inserir a descrição da imagem aqui

1 answer

0


There is a similar example in the Mahapps documentation itself.

XAML

Put the following code inside the tag Controls:MetroWindow in your layout file 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:

inserir a descrição da imagem aqui

Code Behind

In the archive .cs of his Window, add the following code:

private void Username_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    ContextMenu contextMenu = button.ContextMenu;
    contextMenu.PlacementTarget = button;
    contextMenu.IsOpen = true;
    e.Handled = true;
}

private void ChangeUser_Click(object sender, RoutedEventArgs e)
{

}

private void Exit_Click(object sender, RoutedEventArgs e)
{

}

The method Username_Click will display the menu previously created in XAML and the other two methods will be called by clicking on the "Swap user" and "Quit" menu item respectively. Just add the desired code within each method.

Final result

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.