This article describe that how to use Contextmenu control in XAML and Code.A ContextMenu is attached to a specific control. 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,
for example in following Textbox control has Contextmenu with Cut, Copy and paste options that have following task:
Cut : Moves the current selection in the text box to the Clipboard,This method will only cut text from the text box if text is selected in the control. You can use this method, instead of using the Clipboard class, to copy text in the text box and move it to the Clipboard.
Copy: copy the selected text to clipboard.
paste: paste the text that has clipboard.
Create ContextMenu for textBox
[XAML]
<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="300" Width="300" Name="Window1"> <Grid> <TextBox Margin="74,128,84,111" Name="TextBox1" > <TextBox.ContextMenu> <ContextMenu Name="ContextMenu1" StaysOpen="true"> <MenuItem Header="Cut" Name="MenuItemCut" Click="MenuItemCut_Click"/> <MenuItem Header="Copy" Name="MenuItemCopy" Click="MenuItemCopy_Click"/> <MenuItem Header="Paste" Name ="MenuItemPaste" Click="MenuItemPaste_Click"/> </ContextMenu> </TextBox.ContextMenu> </TextBox> </Grid> </Window>
[Code]
Private Sub CreateContextMenu() Dim Contextmenu1 As New ContextMenu Dim MenuItemCut As New MenuItem() MenuItemCut.Header = "Cut" AddHandler MenuItemCut.Click, AddressOf MenuItemCut_Click Dim MenuItemCopy As New MenuItem() MenuItemCopy.Header = "Copy" AddHandler MenuItemCopy.Click, AddressOf MenuItemCopy_Click Dim MenuItemPaste As New MenuItem() MenuItemPaste.Header = "Paste" AddHandler MenuItemPaste.Click, AddressOf MenuItemPaste_Click Contextmenu1.Items.Add(MenuItemCut) Contextmenu1.Items.Add(MenuItemCopy) Contextmenu1.Items.Add(MenuItemPaste) TextBox1.ContextMenu = Contextmenu1 End Sub
Event handling
Private Sub MenuItemCut_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) TextBox1.Cut() End Sub Private Sub MenuItemCopy_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) TextBox1.Copy() End Sub Private Sub MenuItemPaste_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) TextBox1.Paste() End Sub
hi everybody, i don’t understand how fix this error: in file xaml i get “The member “ContextMenu” is not recognized or is not accessible”. This happens either if i set Sub CreateContextMenu to public