ContextMenu in WPF using VB.NET

In this article we will learn how to use ContextMenu in WPF using VB.NET.
  • 2997

In this article we will learn how to use ContextMenu in WPF using VB.NET.


The ContextMenu element enables you to present users with a list of items that specify commands or options that are associated with a particular control. When Users right-click the control to make the menu appear. The event is a right-click on an existing control, element, or item already displayed in the page. A ContextMenu can contain one or more context menu items. Each item is associated with an action to execute client or server-side code. In addition, each context menu item may be displayed with an icon and\or text.

For Example

Taking a TextBox control on the form.

XAML code

<Window x:Class="MainWindow"



    Title="MainWindow" Height="348" Width="525">

    <TextBox Name="textBox1"


         Margin="10, 10, 5, 5" Grid.Row="7" Height="289">

        Rohatash Kumar



                <MenuItem Header="_Bold"



                Unchecked="Bold_Unchecked" />

                <MenuItem Header="_Italic"



                Unchecked="Italic_Unchecked" />

                <Separator />

                <MenuItem Header="I_ncrease Font Size"

                Click="IncreaseFont_Click" />

                <MenuItem Header="_Decrease Font Size"

                Click="DecreaseFont_Click" />






The form looks like this.



Figure 1.


Now double click on the form and add the following code.


Private Sub Bold_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)

        textBox1.FontWeight = FontWeights.Bold

    End Sub


    Private Sub Bold_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)

        textBox1.FontWeight = FontWeights.Normal

    End Sub


    Private Sub Italic_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)

        textBox1.FontStyle = FontStyles.Italic

    End Sub

    Private Sub Italic_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)

        textBox1.FontStyle = FontStyles.Normal

    End Sub

    Private Sub IncreaseFont_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        If textBox1.FontSize < 18 Then

            textBox1.FontSize += 2

        End If

    End Sub

    Private Sub DecreaseFont_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        If textBox1.FontSize > 10 Then

            textBox1.FontSize -= 2

        End If

    End Sub


Now run the application and test it.



Figure 2.


Now right click on the TextBox control. The form looks like this.



Figure 3.


Now applying context-specific Menu bold.



Figure 4.


Now applying italic.



Figure 5.


Now applying increase font size.



Figure 6.


More Articles

© 2020 DotNetHeaven. All rights reserved.