How to add Custom Context Menu with a TextBox in WPF

In this article i am describing about how to add the custom context menu for the your textbox control in your WPF project. Context menu in the textbox is very common functionality, generally we frequently need to textbox that can perform cut and copy from clipboard operation.
Example:
We have to add a custom context menu in a textbox control that has following options:
Cut : Cut the selected text and copy to clipboard.
Copy : Copy the selected text in the textbox to clipboard.
Paste: Paste the data from clipboard.
Enable SpellCheck : Enable spellcheck functionality to textbox.

 

Xaml code :

Here is the code in xaml  for adding custom context menu with a textbox:

<Window x:Class="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="252" Width="460">
        <Grid Background="LightBlue" Height="221" Width="434">
            <TextBox MaxLength="100"  Name="tbMultiLine" Margin="98.5,44,98.5,0" Height="29" VerticalAlignment="Top">
                <TextBox.ContextMenu>
                    <ContextMenu  Name="cMenu1" Opened="cMenuShow" >
                        <MenuItem Header="Cut" Name=”cMenuItemCut”  Click="ClickCut"  />
                        <MenuItem  Header="Copy"  Name=”cMenuItemCopy” Click="ClickCopy"  />
                        <MenuItem  Header="Paste" Name=”cMenuItemPaste” Click="ClickPaste" />
                        <Separator/>
                        <MenuItem  Header="Enable SpellCheck" Name="cMenuItemEnableSpellCheck" Click="ClickEnableSpellChk"  />
                    </ContextMenu>
                </TextBox.ContextMenu>
            </TextBox>
        </Grid>
    </Window>

 VB.net Code :

Private Sub ClickCut(ByVal sender As Object, ByVal args As RoutedEventArgs)
        tbMultiLine.Cut()
End Sub
 
Private Sub ClickCopy(ByVal sender As Object, ByVal args As RoutedEventArgs)
        tbMultiLine.Copy()
End Sub
 
Private Sub ClickPaste(ByVal sender As Object, ByVal args As RoutedEventArgs)
        tbMultiLine.Paste()
End Sub
 
Private Sub ClickEnableSpellChk(ByVal sender As Object, ByVal args As RoutedEventArgs)
        tbMultiLine.SpellCheck.IsEnabled = True
End Sub
 
Private Sub cMenuShow(ByVal sender As Object, ByVal args As RoutedEventArgs)
        If tbMultiLine.SelectedText = "" Then
            cMenuItemCopy.IsEnabled = cMenuItemCut.IsEnabled = False
        Else
            cMenuItemCopy.IsEnabled = cMenuItemCut.IsEnabled = True
            If Clipboard.ContainsText() Then
                cMenuItemPaste.IsEnabled = True
            Else
                cMenuItemPaste.IsEnabled = False
            End If
        End If
End Sub

2 thoughts on “How to add Custom Context Menu with a TextBox in WPF”

  1. Thanks for providing this entry. I very much liked it. Keep up the quality work, dude!

Comments are closed.