Files
docs-desktop/dotnet-desktop-guide/framework/wpf/controls/how-to-use-a-custom-context-menu-with-a-textbox.md
T
Andy De George da363692ff Initial WPF content migrated (#17)
* Reset branch for WPF changes

* Convert BMP to PNG; fix link-out-of-scope err

* Add snippets for WPF... 6794 files!!!!

* Add missing snippets

* update file updated between migration

* Fix paths to include

* update breadcrumb and toc

* fix index links

* fix index links

* fix index links

* fix markdown
2020-09-04 09:46:28 -07:00

2.8 KiB

title, ms.date, dev_langs, helpviewer_keywords, ms.assetid
title ms.date dev_langs helpviewer_keywords ms.assetid
How to: Use a Custom Context Menu with a TextBox 03/30/2017
csharp
vb
context menus [WPF], custom
menus [WPF], custom
custom context menus [WPF]
TextBox control [WPF], custom content menus
842d3cd5-6fa0-4be4-8d90-6c7466213b1c

How to: Use a Custom Context Menu with a TextBox

This example shows how to define and implement a simple custom context menu for a xref:System.Windows.Controls.TextBox.

Example

The following [!INCLUDETLA#tla_xaml] example defines a xref:System.Windows.Controls.TextBox control that includes a custom context menu.

The context menu is defined using a xref:System.Windows.Controls.ContextMenu element. The context menu itself consists of a series of xref:System.Windows.Controls.MenuItem elements and xref:System.Windows.Controls.Separator elements. Each xref:System.Windows.Controls.MenuItem element defines a command in the context menu; the xref:System.Windows.Controls.HeaderedItemsControl.Header%2A attribute defines the display text for the menu command, and the xref:System.Windows.Controls.MenuItem.Click attribute specifies a handler method for each menu item. The xref:System.Windows.Controls.Separator element simply causes a separating line to be rendered between the previous and subsequent menu items.

[!code-xamlTextBox_ContextMenu#_TextBox_ContextMenuXAML]

Example

The following example shows the implementation code for the preceding context menu definition, as well as the code that enables and disables the context menu. The xref:System.Windows.Controls.ContextMenu.Opened event is used to dynamically enable or disable certain commands depending on the current state of the xref:System.Windows.Controls.TextBox.

To restore the default context menu, use the xref:System.Windows.DependencyObject.ClearValue%2A method to clear the value of the xref:System.Windows.FrameworkElement.ContextMenu%2A property. To disable the context menu altogether, set the xref:System.Windows.FrameworkElement.ContextMenu%2A property to a null reference (Nothing in Visual Basic).

[!code-csharpTextBox_ContextMenu#_TextBox_ContextMenu] [!code-vbTextBox_ContextMenu#_TextBox_ContextMenu]

See also