Text​Box Text​Box Text​Box Text​Box Class

Definition

Some information relates to pre-released product which may be substantially modified before it’s commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Prerelease APIs are identified by a Prerelease label.

[Contains prerelease APIs.]
Represents a control that can be used to display and edit plain text (single or multi-line).

public : class TextBox : Control, ITextBox, ITextBox2, ITextBox3, ITextBox4, ITextBox5public class TextBox : Control, ITextBox, ITextBox2, ITextBox3, ITextBox4, ITextBox5Public Class TextBox Inherits Control Implements ITextBox, ITextBox2, ITextBox3, ITextBox4, ITextBox5// This API is not available in Javascript.
<TextBox .../>
Inheritance
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Inherited Members

Inherited properties

Inherited events

Inherited methods

Examples

This example shows a TextBox with a header and placeholder text. The Text from the TextBox is used to show a greeting to the user.

<StackPanel>
    <TextBlock Text="What's your name?"/>
        <StackPanel Orientation="Horizontal" Margin="0,20,0,20">

            <TextBox x:Name="nameInput"
                     Header="Enter your name:" PlaceholderText="Name"
                     Width="300" HorizontalAlignment="Left"/>

            <Button Content="Hello button" Click="Button_Click"/>
        </StackPanel>
    <TextBlock x:Name="greetingOutput"/>
</StackPanel>
private void Button_Click(object sender, RoutedEventArgs e)
{
    greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}

Remarks

Text box control

The TextBox control enables a user to type text into an app. It's typically used to capture a single line of text, but can be configured to capture multiple lines of text. The text displays on the screen in a simple uniform plaintext format.

TextBox has a number of features that can simplify text entry. It comes with a familiar, built-in context menu with support for copying and pasting text. The "clear all" button lets a user quickly delete all text that has been entered. It also has spell checking capabilities built in and enabled by default.

Here's how to create a TextBox in XAML and in code.

<TextBox Width="500" Header="Notes" PlaceholderText="Type your notes here"/>
TextBox textBox = new TextBox();
textBox.Width = 500;
textBox.Header = "Notes";
textBox.PlaceholderText = "Type your notes here";
// Add the TextBox to the visual tree.
rootGrid.Children.Add(textBox);

The resulting TextBox looks like this. The blue border indicates that the TextBox has focus.

A simple text box### Is TextBox the right control to use? You can use a TextBox control to display and edit unformatted text. If you need an editable text box that accepts passwords or other sensitive input, see PasswordBox. If you need a text box to enter search terms, see AutoSuggestBox. If you need to enter or edit formatted text, see RichEditBox.

Use TextBox for data input in a form

It’s common to use a TextBox to accept data input on a form, and use the Text property to get the complete text string from the TextBox. You typically use an event like a submit button Click to access the Text property, but you can handle the TextChanged or TextChanging event if you need to do something when the text changes. You can add a Header (or label) and PlaceholderText (or watermark) to the TextBox to give the user an indication of what the TextBox is for. To customize the look of the header, you can set the HeaderTemplate property instead of Header. For design info, see Guidelines for labels.

You can restrict the number of characters the user can type by setting the MaxLength property. However, MaxLength does not restrict the length of pasted text. Use the Paste event to modify pasted text if this is important for your app.

TextBox includes a clear all button ("x") that appears when text is entered in the box. When a user clicks the "x", the text in the TextBox is cleared. It looks like this.

A text box with a clear all button The clear all button is shown only for editable, single-line text boxes that contain text and have focus. The clear all button is not shown in any of these cases:

Make a TextBox read-only

You can make a TextBox read-only by setting the IsReadOnly property to true. For example, you might have a TextBox for a user to enter comments that is enabled only under certain conditions. You can make the TextBox read-only until the conditions are met. If you need only to display text, consider using a TextBlock or RichTextBlock instead.

Enable multi-line input

There are two properties that control whether the TextBox displays text on more than one line.

  • To let the text box allow and display the newline or return characters, set the AcceptsReturn property to true.
  • To enable text wrapping, set the TextWrapping property to Wrap. (TextBox doesn't support the TextWrapping.WrapWholeWords enumeration value.) A multi-line TextBox will continue to grow vertically as text is entered unless it’s constrained by its Height or MaxHeight property, or by a parent container. You should test that a multi-line TextBox doesn’t grow beyond its visible area, and constrain its growth if it does. Scrolling using a scroll-wheel or touch is automatically enabled when needed. However, vertical scrollbars are not shown by default. You can show the vertical scrollbars by setting the ScrollViewer.VerticalScrollBarVisibility to Auto on the embedded ScrollViewer, as shown here.
<TextBox AcceptsReturn="True" TextWrapping="Wrap" 
         MaxHeight="172" Width="300" Header="Description"
         ScrollViewer.VerticalScrollBarVisibility="Auto"/>
TextBox textBox = new TextBox();
textBox.AcceptsReturn = true;
textBox.TextWrapping = TextWrapping.Wrap;
textBox.MaxHeight = 172;
textBox.Width = 300;
textBox.Header = "Description";
ScrollViewer.SetVerticalScrollBarVisibility(textBox, ScrollBarVisibility.Auto);

Here's what the TextBox looks like after text is added.

A mullti line text box

Format the text display

Use the TextAlignment property to align text within a TextBox. To align the TextBox within the layout of the page, use the HorizontalAlignment and VerticalAlignment properties.

While the TextBox supports only unformatted text, you can customize how the text is displayed in the TextBox to match your branding. You can set standard Control properties like FontFamily, FontSize, FontStyle, Background, Foreground, and CharacterSpacing to change the look of the text. These properties affect only how the TextBox displays the text locally, so if you were to copy and paste the text into a rich text control, for example, no formatting would be applied.

This example shows a read-only TextBox with several properties set to customize the appearance of the text.

<TextBox Text="Sample Text" IsReadOnly="True" 
         FontFamily="Verdana" FontSize="24"
         FontWeight="Bold" FontStyle="Italic" 
         CharacterSpacing="200" Width="300"
         Foreground="Blue" Background="Beige"/>
TextBox textBox = new TextBox();
textBox.Text = "Sample Text";
textBox.IsReadOnly = true;
textBox.FontFamily = new FontFamily("Verdana");
textBox.FontSize = 24;
textBox.FontWeight = Windows.UI.Text.FontWeights.Bold;
textBox.FontStyle = Windows.UI.Text.FontStyle.Italic;
textBox.CharacterSpacing = 200;
textBox.Width = 300;
textBox.Background = new SolidColorBrush(Windows.UI.Colors.Beige);
textBox.Foreground = new SolidColorBrush(Windows.UI.Colors.Blue);
// Add the TextBox to the visual tree.
rootGrid.Children.Add(textBox);

The resulting TextBox looks like this.

A simple text box

Modify the context menu

By default, the commands shown in the TextBox context menu depend on the state of the TextBox. For example, the following commands can be shown when the TextBox is editable.

CommandShown when...
Copytext is selected.
Cuttext is selected.
Pastethe clipboard contains text.
Select allthe TextBox contains text.
Undotext has been changed.

To modify the commands shown in the context menu, handle the ContextMenuOpening event. For an example of this, see Scenario 2 of the ContextMenu sample. For design info, see Guidelines for context menus.

Selection, copy, and paste

You can get or set the selected text in a TextBox using the SelectedText property. Use the SelectionStart and SelectionLength properties, and the Select and SelectAll methods, to manipulate the text selection. Handle the SelectionChanged event to do something when the user selects or de-selects text. You can change the color used to highlight the selected text by setting the SelectionHighlightColor property.

TextBox supports copy and paste by default. You can provide custom handling of the Paste event on editable text controls in your app. For example, you might remove the line breaks from a multi-line address when pasting it into a single-line search box. Or, you might check the length of the pasted text and warn the user if it exceeds the maximum length that can be saved to a database. For more info and examples, see the Paste event.

Use a text box with the touch keyboard

The touch keyboard can be used for text entry when your app runs on a device with a touch screen. TextBox provides properties you can set to make it much faster and easier for users to enter data in your app using the touch keyboard. Set the InputScope property to match the kind of data the user is expected to enter. For example, if a TextBox is used only to enter a 4-digit PIN, set the InputScope property to Number. This tells the system to show the number keypad layout, which makes it easier for the user to enter the PIN.

Other properties that affect the touch keyboard are IsSpellCheckEnabled, IsTextPredictionEnabled, and PreventKeyboardDisplayOnProgrammaticFocus. (IsSpellCheckEnabled also affects the TextBox when a hardware keyboard is used.) For more info and examples, see Use input scope to change the touch keyboard, and the property documentation.

Control style and template

You can modify the default Style and ControlTemplate to give the control a unique appearance. For information about modifying a control's style and template, see Styling controls. The default style, template, and resources that define the look of the control are included in the generic.xaml file. For design purposes, generic.xaml is available in the (Program Files)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP&lt;SDK version>\Generic folder from a Windows Software Development Kit (SDK) installation. Styles and resources from different versions of the SDK might have different values.

Starting in Windows 10, version 1607 (Windows Software Development Kit (SDK) version 10.0.14393.0), generic.xaml includes resources that you can use to modify the colors of a control in different visual states without modifying the control template. In apps that target this software development kit (SDK) or later, modifying these resources is preferred to setting properties such as Background and Foreground. For more info, see the Light-weight styling section of the Styling controls article.

This table shows the resources used by the TextBox control. Resources that start with "TextControl" are shared by TextBox, PasswordBox, RichEditBox, and AutoSuggestBox.

Resource keyDescription
TextControlForegroundText color at rest and not focused
TextControlForegroundPointerOverText color on hover
TextControlForegroundFocusedText color when focused
TextControlForegroundDisabledText color when disabled
TextControlBackgroundBackground color at rest and not focused
TextControlBackgroundPointerOverBackground color on hover
TextControlBackgroundFocusedBackground color when focused
TextControlBackgroundDisabledBackground color when disabled
TextControlBorderBrushBorder color at rest and not focused
TextControlBorderBrushPointerOverBorder color on hover
TextControlBorderBrushFocusedBorder color when focused
TextControlBorderBrushDisabledBorder color when disabled
TextControlPlaceholderForegroundPlaceholder text color at rest and not focused
TextControlPlaceholderForegroundPointerOverPlaceholder text color on hover
TextControlPlaceholderForegroundFocusedPlaceholder text color when focused
TextControlPlaceholderForegroundDisabledPlaceholder text color when disabled
TextControlHeaderForegroundHeader text color
TextControlHeaderForegroundDisabledHeader text color when disabled
TextControlSelectionHighlightColorHighlight color of selected text
TextControlButtonBackgroundBackground color of delete button at rest
TextControlButtonBackgroundPointerOverBackground color of delete button on hover
TextControlButtonBackgroundPressedBackground color of delete button when pressed
TextControlButtonBorderBrushBorder color of delete button at rest
TextControlButtonBorderBrushPointerOverBorder color of delete button on hover
TextControlButtonBorderBrushPressedBorder color of delete button when pressed
TextControlButtonForegroundForeground color of delete button at rest
TextControlButtonForegroundPointerOverForeground color of delete button on hover
TextControlButtonForegroundPressedForeground color of delete button when pressed

Constructors

TextBox() TextBox() TextBox() TextBox()

Initializes a new instance of the TextBox class.

public : TextBox()public TextBox()Public Sub New()// This API is not available in Javascript.

Properties

AcceptsReturn AcceptsReturn AcceptsReturn AcceptsReturn

Gets or sets the value that determines whether the text box allows and displays the newline or return characters.

public : PlatForm::Boolean AcceptsReturn { get; set; }public bool AcceptsReturn { get; set; }Public ReadWrite Property AcceptsReturn As bool// This API is not available in Javascript.
<TextBox AcceptsReturn="bool"/>
Value
PlatForm::Boolean bool bool bool

true if the text box allows newline characters; otherwise, false. The default is false.

Remarks

If you change the AcceptsReturn property to true, text might be displayed differently due to text containing newline characters.

You can enable multi-line text in a TextBox control by using the AcceptsReturn property. Use the ScrollViewer.HorizontalScrollBarVisibility or ScrollViewer.VerticalScrollBarVisibility attached properties to change scrollbar behavior. By default the scrollbars appear when the layout system calculates that the text exceeds the dimensions of the viewport for the TextBox.

See Also

AcceptsReturnProperty AcceptsReturnProperty AcceptsReturnProperty AcceptsReturnProperty

Identifies the AcceptsReturn dependency property.

public : static DependencyProperty AcceptsReturnProperty { get; }public static DependencyProperty AcceptsReturnProperty { get; }Public Static ReadOnly Property AcceptsReturnProperty As DependencyProperty// This API is not available in Javascript.

CharacterCasing CharacterCasing CharacterCasing CharacterCasing

Prerelease. Gets or sets a value that indicates how the control modifies the case of characters as they are typed.

public : CharacterCasing CharacterCasing { get; set; }public CharacterCasing CharacterCasing { get; set; }Public ReadWrite Property CharacterCasing As CharacterCasing// This API is not available in Javascript.
<TextBox CharacterCasing="characterCasingValue"/>

Value
CharacterCasing CharacterCasing CharacterCasing CharacterCasing

A value of the enumeration that indicates how the control modifies the case of characters as they are typed. The default is Normal, which indicates that the charcters are not changed.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

Remarks

Note

This property modifies the case of characters as they are typed. It doesn’t modify characters that are entered in other ways, like paste or ink.

CharacterCasingProperty CharacterCasingProperty CharacterCasingProperty CharacterCasingProperty

Prerelease. Identifies the CharacterCasing dependency property.

public : static DependencyProperty CharacterCasingProperty { get; }public static DependencyProperty CharacterCasingProperty { get; }Public Static ReadOnly Property CharacterCasingProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CharacterCasing dependency property.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

DesiredCandidateWindowAlignment DesiredCandidateWindowAlignment DesiredCandidateWindowAlignment DesiredCandidateWindowAlignment

Gets or sets a value that indicates the preferred alignment of the Input Method Editor (IME).

public : CandidateWindowAlignment DesiredCandidateWindowAlignment { get; set; }public CandidateWindowAlignment DesiredCandidateWindowAlignment { get; set; }Public ReadWrite Property DesiredCandidateWindowAlignment As CandidateWindowAlignment// This API is not available in Javascript.
<TextBox DesiredCandidateWindowAlignment="candidateWindowAlignmentMemberName"/>
Value
CandidateWindowAlignment CandidateWindowAlignment CandidateWindowAlignment CandidateWindowAlignment

A value of the enumeration that indicates the preferred alignment of the Input Method Editor (IME). The default is Default.

Remarks

Users sometimes enter text through an Input Method Editor (IME) that shows in a window just below a text input box (typically for East Asian languages). The Input Method Editor (IME) window can cover important parts of your app UI that the user might need to see while entering text. Use the DesiredCandidateWindowAlignment property to specify a preferred placement of the Input Method Editor (IME) window in relation to the text input box.

By default, when the hardware keyboard is used, the Input Method Editor (IME) follows the cursor. You can set DesiredCandidateWindowAlignment to BottomEdge to align the Input Method Editor (IME) to the bottom edge and left side of the text edit control.

When the Soft Input Panel (SIP) is used, DesiredCandidateWindowAlignment doesn't have any effect. The Input Method Editor (IME) remains docked to the Soft Input Panel (SIP) whenever the Soft Input Panel (SIP) is used.

You can also handle the CandidateWindowBoundsChanged event to adapt your UI to the placement of the Input Method Editor (IME).

See Also

DesiredCandidateWindowAlignmentProperty DesiredCandidateWindowAlignmentProperty DesiredCandidateWindowAlignmentProperty DesiredCandidateWindowAlignmentProperty

Identifies the DesiredCandidateWindowAlignment dependency property.

public : static DependencyProperty DesiredCandidateWindowAlignmentProperty { get; }public static DependencyProperty DesiredCandidateWindowAlignmentProperty { get; }Public Static ReadOnly Property DesiredCandidateWindowAlignmentProperty As DependencyProperty// This API is not available in Javascript.
See Also

Header Header Header Header

Gets or sets the content for the control's header.

public : PlatForm::Object Header { get; set; }public object Header { get; set; }Public ReadWrite Property Header As object// This API is not available in Javascript.
<TextBox Header="headerString"/>

Value
PlatForm::Object object object object

The content of the control's header. The default is null.

Remarks

You can set a data template for the Header by using the HeaderTemplate property.

See Also

HeaderProperty HeaderProperty HeaderProperty HeaderProperty

Identifies the Header dependency property.

public : static DependencyProperty HeaderProperty { get; }public static DependencyProperty HeaderProperty { get; }Public Static ReadOnly Property HeaderProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Header dependency property.

HeaderTemplate HeaderTemplate HeaderTemplate HeaderTemplate

Gets or sets the DataTemplate used to display the content of the control's header.

public : DataTemplate HeaderTemplate { get; set; }public DataTemplate HeaderTemplate { get; set; }Public ReadWrite Property HeaderTemplate As DataTemplate// This API is not available in Javascript.
<TextBox>
  <TextBox.HeaderTemplate>
    singleDataTemplate
  </TextBox.HeaderTemplate>
</TextBox>
Value
DataTemplate DataTemplate DataTemplate DataTemplate

The template that specifies the visualization of the header object. The default is null.

See Also

HeaderTemplateProperty HeaderTemplateProperty HeaderTemplateProperty HeaderTemplateProperty

Identifies the HeaderTemplate dependency property.

public : static DependencyProperty HeaderTemplateProperty { get; }public static DependencyProperty HeaderTemplateProperty { get; }Public Static ReadOnly Property HeaderTemplateProperty As DependencyProperty// This API is not available in Javascript.

HorizontalTextAlignment HorizontalTextAlignment HorizontalTextAlignment HorizontalTextAlignment

Prerelease. Gets or sets a value that indicates how text is aligned in the TextBox.

public : TextAlignment HorizontalTextAlignment { get; set; }public TextAlignment HorizontalTextAlignment { get; set; }Public ReadWrite Property HorizontalTextAlignment As TextAlignment// This API is not available in Javascript.
<TextBox HorizontalTextAlignment="textAlignmentValue"/>

Value
TextAlignment TextAlignment TextAlignment TextAlignment

One of the TextAlignment enumeration values that specifies how text is aligned. The default is Left.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

Remarks

This property supports XAML Standard. It provides the same functionality as the TextAlignement property. If both properties are set to conflicting values, the last one set is used.

HorizontalTextAlignmentProperty HorizontalTextAlignmentProperty HorizontalTextAlignmentProperty HorizontalTextAlignmentProperty

Prerelease. Identifies the HorizontalTextAlignment dependency property.

public : static DependencyProperty HorizontalTextAlignmentProperty { get; }public static DependencyProperty HorizontalTextAlignmentProperty { get; }Public Static ReadOnly Property HorizontalTextAlignmentProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the HorizontalTextAlignment dependency property.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

InputScope InputScope InputScope InputScope

Gets or sets the context for input used by this TextBox.

public : InputScope InputScope { get; set; }public InputScope InputScope { get; set; }Public ReadWrite Property InputScope As InputScope// This API is not available in Javascript.
<TextBox InputScope="inputScopeName" .../>
Value
InputScope InputScope InputScope InputScope

The input scope, which provides a hint at the type of text input expected by the control.

Examples

Here's how to set the InputScope in XAML and in code.

<TextBox Header="Telephone Number" InputScope="TelephoneNumber"/>

TextBox phoneNumberTextBox = new TextBox();
phoneNumberTextBox.Header="Telephone Number";

InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(scopeName);
phoneNumberTextBox.InputScope = scope;

Remarks

The input scope provides a hint at the type of text input expected by the control. Various elements of the system can respond to the hint provided by the input scope and provide a specialized UI for the input type. For example, the touch keyboard might show a number pad for text input when the control has its InputScope set to Number.

The control might also interpret the data being entered differently (typically for East Asian related input scopes). The input scope does not perform any validation, and does not prevent the user from providing any input through a hardware keyboard or other input device.

Other properties that affect the touch keyboard are IsSpellCheckEnabled, IsTextPredictionEnabled, and PreventKeyboardDisplayOnProgrammaticFocus. For more info and examples, see Use input scope to change the touch keyboard.

See Also

InputScopeProperty InputScopeProperty InputScopeProperty InputScopeProperty

Identifies the InputScope dependency property.

public : static DependencyProperty InputScopeProperty { get; }public static DependencyProperty InputScopeProperty { get; }Public Static ReadOnly Property InputScopeProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the InputScope dependency property.

IsColorFontEnabled IsColorFontEnabled IsColorFontEnabled IsColorFontEnabled

Gets or sets a value that determines whether font glyphs that contain color layers, such as Segoe UI Emoji, are rendered in color.

public : PlatForm::Boolean IsColorFontEnabled { get; set; }public bool IsColorFontEnabled { get; set; }Public ReadWrite Property IsColorFontEnabled As bool// This API is not available in Javascript.
<TextBox IsColorFontEnabled="bool" />
Value
PlatForm::Boolean bool bool bool

true if color glyphs show in color; otherwise, false. The default is true.

Remarks

Windows 8.1 introduces the ability for fonts to include multiple colored layers for each glyph. For example, the Segoe UI Emoji font defines color versions of the Emoticon and other Emoji characters. By default, the IsColorFontEnabled property is true and fonts with these additional layers are rendered in color.

In Windows 8, Extensible Application Markup Language (XAML) text controls don't render multi-color fonts in color. When an app that was compiled for Windows 8 is recompiled for Windows 8.1, color rendering of multi-color fonts is enabled by default. Some glyphs in multi-color fonts have different layout metrics when rendered in color. This could cause different layout in apps when they are recompiled for Windows 8.1. To retain the Windows 8 behavior when your app is recompiled for Windows 8.1, set IsColorFontEnabled to false.

IsColorFontEnabledProperty IsColorFontEnabledProperty IsColorFontEnabledProperty IsColorFontEnabledProperty

Identifies the IsColorFontEnabled dependency property.

public : static DependencyProperty IsColorFontEnabledProperty { get; }public static DependencyProperty IsColorFontEnabledProperty { get; }Public Static ReadOnly Property IsColorFontEnabledProperty As DependencyProperty// This API is not available in Javascript.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

Gets or sets the value that determines if the user can change the text in the text box.

public : PlatForm::Boolean IsReadOnly { get; set; }public bool IsReadOnly { get; set; }Public ReadWrite Property IsReadOnly As bool// This API is not available in Javascript.
<TextBox IsReadOnly="bool"/>
Value
PlatForm::Boolean bool bool bool

true if the text box is read-only; otherwise, false. The default is false.

Remarks

The default control template for TextBox has a visual state that tracks whether the TextBox is read-only. If the TextBox is read-only, it appears in a gray color in most themes. This also tracks if Control.IsEnabled is false.

See Also

IsReadOnlyProperty IsReadOnlyProperty IsReadOnlyProperty IsReadOnlyProperty

Identifies the IsReadOnly dependency property.

public : static DependencyProperty IsReadOnlyProperty { get; }public static DependencyProperty IsReadOnlyProperty { get; }Public Static ReadOnly Property IsReadOnlyProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the IsReadOnly dependency property.

IsSpellCheckEnabled IsSpellCheckEnabled IsSpellCheckEnabled IsSpellCheckEnabled

Gets or sets a value that specifies whether the TextBox input interacts with a spell check engine.

public : PlatForm::Boolean IsSpellCheckEnabled { get; set; }public bool IsSpellCheckEnabled { get; set; }Public ReadWrite Property IsSpellCheckEnabled As bool// This API is not available in Javascript.
<TextBox IsSpellCheckEnabled="bool" />
Value
PlatForm::Boolean bool bool bool

true if the TextBox input interacts with a spell check engine; otherwise, false. The default is true.

Remarks

When using the Soft Input Panel (SIP), this property enables the following features:

  • auto-cap (Mobile only)
  • spell check
  • auto-correction
  • spelling candidates on-demand when the user taps on a misspelled word

Windows 8 For Universal Windows 8 app, the default is false.

See Also

IsSpellCheckEnabledProperty IsSpellCheckEnabledProperty IsSpellCheckEnabledProperty IsSpellCheckEnabledProperty

Identifies the IsSpellCheckEnabled dependency property.

public : static DependencyProperty IsSpellCheckEnabledProperty { get; }public static DependencyProperty IsSpellCheckEnabledProperty { get; }Public Static ReadOnly Property IsSpellCheckEnabledProperty As DependencyProperty// This API is not available in Javascript.

IsTextPredictionEnabled IsTextPredictionEnabled IsTextPredictionEnabled IsTextPredictionEnabled

Gets or sets a value that determines whether text prediction features ("autocomplete") should be enabled for this TextBox.

public : PlatForm::Boolean IsTextPredictionEnabled { get; set; }public bool IsTextPredictionEnabled { get; set; }Public ReadWrite Property IsTextPredictionEnabled As bool// This API is not available in Javascript.
<TextBox IsTextPredictionEnabled="bool" />
Value
PlatForm::Boolean bool bool bool

true to enable text prediction features, otherwise, false. The default is true.

Remarks

Text prediction is not enabled if the user is using a physical keyboard device.

Text prediction is built-in for the@Windows.UI.Xaml.Controls.TextBox?text=TextBox control, using language-specific dictionaries. Setting the value to true doesn't automatically enable the feature on a custom class.

This property doesn't affect Input Method Editor (IME) for Japanese or Chinese languages. Text prediction for these languages is shown even if this property is false.

See Also

IsTextPredictionEnabledProperty IsTextPredictionEnabledProperty IsTextPredictionEnabledProperty IsTextPredictionEnabledProperty

Identifies the IsTextPredictionEnabled dependency property.

public : static DependencyProperty IsTextPredictionEnabledProperty { get; }public static DependencyProperty IsTextPredictionEnabledProperty { get; }Public Static ReadOnly Property IsTextPredictionEnabledProperty As DependencyProperty// This API is not available in Javascript.

MaxLength MaxLength MaxLength MaxLength

Gets or sets the value that specifies the maximum number of characters allowed for user input.

public : int MaxLength { get; set; }public int MaxLength { get; set; }Public ReadWrite Property MaxLength As int// This API is not available in Javascript.
<TextBox MaxLength="int"/>
Value
int int int int

The maximum number of characters allowed for user input. The default is 0 (no limit).

Remarks

A MaxLength value of 0 specifies that there is no limit on the number of characters allowed for user input.

MaxLengthProperty MaxLengthProperty MaxLengthProperty MaxLengthProperty

Identifies the MaxLength dependency property.

public : static DependencyProperty MaxLengthProperty { get; }public static DependencyProperty MaxLengthProperty { get; }Public Static ReadOnly Property MaxLengthProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the MaxLength dependency property.

PlaceholderForeground PlaceholderForeground PlaceholderForeground PlaceholderForeground

Prerelease. Gets or sets a brush that describes the color of placeholder text.

public : Brush PlaceholderForeground { get; set; }public Brush PlaceholderForeground { get; set; }Public ReadWrite Property PlaceholderForeground As Brush// This API is not available in Javascript.
<TextBox PlaceholderForeground="{StaticResource resourceName}"/>

Value
Brush Brush Brush Brush

The brush that describes the color of placeholder text.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

PlaceholderForegroundProperty PlaceholderForegroundProperty PlaceholderForegroundProperty PlaceholderForegroundProperty

Prerelease. Identifies the PlaceholderForeground dependency property.

public : static DependencyProperty PlaceholderForegroundProperty { get; }public static DependencyProperty PlaceholderForegroundProperty { get; }Public Static ReadOnly Property PlaceholderForegroundProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the PlaceholderForeground dependency property.

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

PlaceholderText PlaceholderText PlaceholderText PlaceholderText

Gets or sets the text that is displayed in the control until the value is changed by a user action or some other operation.

public : PlatForm::String PlaceholderText { get; set; }public string PlaceholderText { get; set; }Public ReadWrite Property PlaceholderText As string// This API is not available in Javascript.
<TextBox PlaceholderText="placeholderString"/>

Value
PlatForm::String string string string

The text that is displayed in the control when no value is entered. The default is an empty string ("").

PlaceholderTextProperty PlaceholderTextProperty PlaceholderTextProperty PlaceholderTextProperty

Identifies the PlaceholderText dependency property.

public : static DependencyProperty PlaceholderTextProperty { get; }public static DependencyProperty PlaceholderTextProperty { get; }Public Static ReadOnly Property PlaceholderTextProperty As DependencyProperty// This API is not available in Javascript.

PreventKeyboardDisplayOnProgrammaticFocus PreventKeyboardDisplayOnProgrammaticFocus PreventKeyboardDisplayOnProgrammaticFocus PreventKeyboardDisplayOnProgrammaticFocus

Gets or sets a value that indicates whether the on-screen keyboard is shown when the control receives focus programmatically.

public : PlatForm::Boolean PreventKeyboardDisplayOnProgrammaticFocus { get; set; }public bool PreventKeyboardDisplayOnProgrammaticFocus { get; set; }Public ReadWrite Property PreventKeyboardDisplayOnProgrammaticFocus As bool// This API is not available in Javascript.
<TextBox PreventKeyboardDisplayOnProgrammaticFocus="bool"/>
Value
PlatForm::Boolean bool bool bool

true if the on-screen keyboard is not shown when the control receives focus programmatically; otherwise, false. The default is false.

Remarks

Set this property to true to prevent the onscreen touch keyboard from showing when focus is programmatically set on a text box. By default, the onscreen touch keyboard is displayed whenever focus moves to an editable text box and the most recent input was generated by touch. This happens whether focus is set programmatically or by user interaction. In some situations, you might not want the keyboard to show when focus is set programmatically. For example, you might want to prevent the keyboard from covering part of your UI until the user is ready to continue their interaction.

PreventKeyboardDisplayOnProgrammaticFocusProperty PreventKeyboardDisplayOnProgrammaticFocusProperty PreventKeyboardDisplayOnProgrammaticFocusProperty PreventKeyboardDisplayOnProgrammaticFocusProperty

Identifies the PreventKeyboardDisplayOnProgrammaticFocus dependency property.

public : static DependencyProperty PreventKeyboardDisplayOnProgrammaticFocusProperty { get; }public static DependencyProperty PreventKeyboardDisplayOnProgrammaticFocusProperty { get; }Public Static ReadOnly Property PreventKeyboardDisplayOnProgrammaticFocusProperty As DependencyProperty// This API is not available in Javascript.

SelectedText SelectedText SelectedText SelectedText

Gets or sets the content of the current selection in the text box.

public : PlatForm::String SelectedText { get; set; }public string SelectedText { get; set; }Public ReadWrite Property SelectedText As string// This API is not available in Javascript.
<TextBox SelectedText="string"/>
Value
PlatForm::String string string string

The currently selected text in the text box. If no text is selected, the value is String.Empty.

SelectionHighlightColor SelectionHighlightColor SelectionHighlightColor SelectionHighlightColor

Gets or sets the brush used to highlight the selected text.

public : SolidColorBrush SelectionHighlightColor { get; set; }public SolidColorBrush SelectionHighlightColor { get; set; }Public ReadWrite Property SelectionHighlightColor As SolidColorBrush// This API is not available in Javascript.
<TextBox SelectionHighlightColor="{StaticResource resourceName}"/>

Value
SolidColorBrush SolidColorBrush SolidColorBrush SolidColorBrush

The brush used to highlight the selected text. The practical default is a brush using the theme resource TextSelectionHighlightThemeColor.

Remarks

The control template sets the default selection highlight color to the system resource TextSelectionHighlightColorThemeBrush. To change the selection highlight color for all editable text controls in your app, you can override the TextSelectionHighlightColorThemeBrush system resource in App.xaml. This will affect PasswordBox, TextBox, and RichEditBox controls.

See Also

SelectionHighlightColorProperty SelectionHighlightColorProperty SelectionHighlightColorProperty SelectionHighlightColorProperty

Identifies the SelectionHighlightColor dependency property.

public : static DependencyProperty SelectionHighlightColorProperty { get; }public static DependencyProperty SelectionHighlightColorProperty { get; }Public Static ReadOnly Property SelectionHighlightColorProperty As DependencyProperty// This API is not available in Javascript.

SelectionHighlightColorWhenNotFocused SelectionHighlightColorWhenNotFocused SelectionHighlightColorWhenNotFocused SelectionHighlightColorWhenNotFocused

Gets or sets the brush used to highlight the selected text when the TextBox does not have focus.

public : SolidColorBrush SelectionHighlightColorWhenNotFocused { get; set; }public SolidColorBrush SelectionHighlightColorWhenNotFocused { get; set; }Public ReadWrite Property SelectionHighlightColorWhenNotFocused As SolidColorBrush// This API is not available in Javascript.
<TextBox SelectionHighlightColorWhenNotFocused="{StaticResource resourceName}"/>

Value
SolidColorBrush SolidColorBrush SolidColorBrush SolidColorBrush

The brush used to highlight the selected text when TextBox loses focus. The default is a null brush from a pure code perspective, but the default control template for TextBox applies a Transparent brush for this in a runtime instance of a TextBox control. To disable the SelectionHighlightColorWhenNotFocused, set the brush to Transparent once again.

Additional features and requirements
Device family
Windows 10 Creators Update (introduced v10.0.15063.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v4)
See Also

SelectionHighlightColorWhenNotFocusedProperty SelectionHighlightColorWhenNotFocusedProperty SelectionHighlightColorWhenNotFocusedProperty SelectionHighlightColorWhenNotFocusedProperty

Identifies the SelectionHighlightColorWhenNotFocused dependency property.

public : static DependencyProperty SelectionHighlightColorWhenNotFocusedProperty { get; }public static DependencyProperty SelectionHighlightColorWhenNotFocusedProperty { get; }Public Static ReadOnly Property SelectionHighlightColorWhenNotFocusedProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the SelectionHighlightColorWhenNotFocused dependency property.

Additional features and requirements
Device family
Windows 10 Creators Update (introduced v10.0.15063.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v4)

SelectionLength SelectionLength SelectionLength SelectionLength

Gets or sets the number of characters in the current selection in the text box.

public : int SelectionLength { get; set; }public int SelectionLength { get; set; }Public ReadWrite Property SelectionLength As int// This API is not available in Javascript.
<TextBox SelectionLength="int"/>
Value
int int int int

The number of characters in the current selection in the text box, or 0 if there is no selection.

SelectionStart SelectionStart SelectionStart SelectionStart

Gets or sets the starting position of the text selected in the text box.

public : int SelectionStart { get; set; }public int SelectionStart { get; set; }Public ReadWrite Property SelectionStart As int// This API is not available in Javascript.
<TextBox SelectionStart="int"/>
Value
int int int int

The starting position of the current selection.

Text Text Text Text

Gets or sets the text contents of the text box.

public : PlatForm::String Text { get; set; }public string Text { get; set; }Public ReadWrite Property Text As string// This API is not available in Javascript.
<TextBox Text="string"/>
Value
PlatForm::String string string string

A string containing the text contents of the text box. The default is an empty string ("").

TextAlignment TextAlignment TextAlignment TextAlignment

Gets or sets how the text should be horizontally aligned in the text box.

public : TextAlignment TextAlignment { get; set; }public TextAlignment TextAlignment { get; set; }Public ReadWrite Property TextAlignment As TextAlignment// This API is not available in Javascript.
<TextBox TextAlignment="textAlignmentMemberName"/>
Value
TextAlignment TextAlignment TextAlignment TextAlignment

One of the TextAlignment enumeration values. The default is Left.

TextAlignmentProperty TextAlignmentProperty TextAlignmentProperty TextAlignmentProperty

Identifies the TextAlignment dependency property.

public : static DependencyProperty TextAlignmentProperty { get; }public static DependencyProperty TextAlignmentProperty { get; }Public Static ReadOnly Property TextAlignmentProperty As DependencyProperty// This API is not available in Javascript.

TextProperty TextProperty TextProperty TextProperty

Identifies the Text dependency property.

public : static DependencyProperty TextProperty { get; }public static DependencyProperty TextProperty { get; }Public Static ReadOnly Property TextProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Text dependency property.

TextReadingOrder TextReadingOrder TextReadingOrder TextReadingOrder

Gets or sets a value that indicates how the reading order is determined for the TextBox.

public : TextReadingOrder TextReadingOrder { get; set; }public TextReadingOrder TextReadingOrder { get; set; }Public ReadWrite Property TextReadingOrder As TextReadingOrder// This API is not available in Javascript.
<TextBox TextReadingOrder="textReadingOrderValue"/>
Value
TextReadingOrder TextReadingOrder TextReadingOrder TextReadingOrder

A value that indicates how the reading order is determined for the TextBox. The default is DetectFromContent.

Remarks

This property can be useful when the base direction of the text is unknown, and may not match the user's language or direction. For more info, see the Remarks section of the TextReadingOrder enumeration or How to support bidirectional UI.

See Also

TextReadingOrderProperty TextReadingOrderProperty TextReadingOrderProperty TextReadingOrderProperty

Identifies the TextReadingOrder dependency property.

public : static DependencyProperty TextReadingOrderProperty { get; }public static DependencyProperty TextReadingOrderProperty { get; }Public Static ReadOnly Property TextReadingOrderProperty As DependencyProperty// This API is not available in Javascript.
See Also

TextWrapping TextWrapping TextWrapping TextWrapping

Gets or sets how line breaking occurs if a line of text extends beyond the available width of the text box.

public : TextWrapping TextWrapping { get; set; }public TextWrapping TextWrapping { get; set; }Public ReadWrite Property TextWrapping As TextWrapping// This API is not available in Javascript.
<TextBlock TextWrapping="Wrap"/>
-or-
<TextBlock TextWrapping="NoWrap"/>
Value
TextWrapping TextWrapping TextWrapping TextWrapping

One of the TextWrapping values. The default is NoWrap.

Examples

The following example shows how you can use the TextWrapping property in XAML.

<StackPanel>
    <TextBox Text="A text box that demonstrates TextWrapping, TextAlignment, MaxLength, and AcceptsReturn"  
             TextWrapping="Wrap" TextAlignment="Center" 
             MaxLength="500" AcceptsReturn="True" 
             Margin="20,20,0,0" Width="300" Height="50"/>
</StackPanel>

Remarks

TextBox and RichEditBox don't support the WrapWholeWords value for their TextWrapping properties. If you try to use WrapWholeWords as a value for TextBox.TextWrapping or RichEditBox.TextWrapping, an exception is thrown.

TextWrappingProperty TextWrappingProperty TextWrappingProperty TextWrappingProperty

Identifies the TextWrapping dependency property.

public : static DependencyProperty TextWrappingProperty { get; }public static DependencyProperty TextWrappingProperty { get; }Public Static ReadOnly Property TextWrappingProperty As DependencyProperty// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the TextWrapping dependency property.

Methods

GetLinguisticAlternativesAsync() GetLinguisticAlternativesAsync() GetLinguisticAlternativesAsync() GetLinguisticAlternativesAsync()

Asynchronously gets a list of candidate words based on the provided phonetic characters in an Input Method Editor (IME).

public : IAsyncOperation<IVectorView<PlatForm::String>> GetLinguisticAlternativesAsync()public IAsyncOperation<IReadOnlyList<string>> GetLinguisticAlternativesAsync()Public Function GetLinguisticAlternativesAsync() As IAsyncOperation( Of IReadOnlyListstring )// This API is not available in Javascript.
Returns
IAsyncOperation<IVectorView<PlatForm::String>> IAsyncOperation<IReadOnlyList<string>> IAsyncOperation<IReadOnlyList<string>> IAsyncOperation<IReadOnlyList<string>>

A list of candidate words based on the provided phonetic characters in an Input Method Editor (IME).

Additional features and requirements
Device family
Windows 10 (introduced v10.0.10586.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v2)

GetRectFromCharacterIndex(Int32, Boolean) GetRectFromCharacterIndex(Int32, Boolean) GetRectFromCharacterIndex(Int32, Boolean) GetRectFromCharacterIndex(Int32, Boolean)

Returns a rectangular region for the leading or trailing edge of a character at a specific character index.

public : Rect GetRectFromCharacterIndex(int charIndex, bool trailingEdge)public Rect GetRectFromCharacterIndex(Int32 charIndex, Boolean trailingEdge)Public Function GetRectFromCharacterIndex(charIndex As Int32, trailingEdge As Boolean) As Rect// This API is not available in Javascript.
Parameters
charIndex
int Int32 Int32 Int32

A zero-based index of the character for which to retrieve the rectangle.

trailingEdge
bool Boolean Boolean Boolean

true to get the trailing edge; false to get the leading edge of the character.

Returns

A rectangle for the edge of the character at the specified index.

Examples

This example shows how to use GetRectFromCharacterIndex to determine the rectangle for the selected text. For the complete example, see Scenario 2 of the ContextMenu sample.

// Returns a rect for selected text.
// If no text is selected, returns caret location.
// Text box should not be empty.
private Rect GetTextboxSelectionRect(TextBox textbox)
{
    Rect rectFirst, rectLast;
    if (textbox.SelectionStart == textbox.Text.Length)
    {
        rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart - 1, true);
    }
    else
    {
        rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false);
    }

    int lastIndex = textbox.SelectionStart + textbox.SelectionLength;
    if (lastIndex == textbox.Text.Length)
    {
        rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true);
    }
    else
    {
        rectLast = textbox.GetRectFromCharacterIndex(lastIndex, false);
    }

    GeneralTransform buttonTransform = textbox.TransformToVisual(null);
    Point point = buttonTransform.TransformPoint(new Point());

    // Make sure that we return a valid rect if selection is on multiple lines
    // and end of the selection is to the left of the start of the selection.
    double x, y, dx, dy;
    y = point.Y + rectFirst.Top;
    dy = rectLast.Bottom - rectFirst.Top;
    if (rectLast.Right > rectFirst.Left)
    {
        x = point.X + rectFirst.Left;
        dx = rectLast.Right - rectFirst.Left;
    }
    else
    {
        x = point.X + rectLast.Right;
        dx = rectFirst.Left - rectLast.Right;
    }

    return new Rect(x, y, dx, dy);
}

Remarks

To override the context menu, you can handle the ContextMenuOpening event and replace the default menu with a custom menu. Use GetRectFromCharacterIndex to determine where to position the custom menu. For an example of this, see Scenario 2 of the ContextMenu sample. For design info, see Guidelines for context menus.

Because this method returns a rectangle that represents a character edge, the width of the rectangle that's returned is always 0. To get the width of a character, you must subtract the X value of the leading Rect from the X value of the trailing Rect.

Select(Int32, Int32) Select(Int32, Int32) Select(Int32, Int32) Select(Int32, Int32)

Selects a range of text in the text box.

public : void Select(int start, int length)public void Select(Int32 start, Int32 length)Public Function Select(start As Int32, length As Int32) As void// This API is not available in Javascript.
Parameters
start
int Int32 Int32 Int32

The zero-based index of the first character in the selection.

length
int Int32 Int32 Int32

The length of the selection, in characters.

SelectAll() SelectAll() SelectAll() SelectAll()

Selects the entire contents of the text box.

public : void SelectAll()public void SelectAll()Public Function SelectAll() As void// This API is not available in Javascript.

Events

BeforeTextChanging BeforeTextChanging BeforeTextChanging BeforeTextChanging

Prerelease. Occurs synchronously when the text in the text box starts to change, but before the Text property is updated.

public : event TypedEventHandler BeforeTextChanging<TextBox,  TextBoxBeforeTextChangingEventArgs>public event TypedEventHandler BeforeTextChanging<TextBox,  TextBoxBeforeTextChangingEventArgs>Public Event BeforeTextChanging<TextBox,  TextBoxBeforeTextChangingEventArgs>// This API is not available in Javascript.
<TextBox BeforeTextChanging="eventhandler"/>

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

CandidateWindowBoundsChanged CandidateWindowBoundsChanged CandidateWindowBoundsChanged CandidateWindowBoundsChanged

Occurs when the Input Method Editor (IME) window open, updates, or closes.

public : event TypedEventHandler CandidateWindowBoundsChanged<TextBox,  CandidateWindowBoundsChangedEventArgs>public event TypedEventHandler CandidateWindowBoundsChanged<TextBox,  CandidateWindowBoundsChangedEventArgs>Public Event CandidateWindowBoundsChanged<TextBox,  CandidateWindowBoundsChangedEventArgs>// This API is not available in Javascript.
<TextBox CandidateWindowBoundsChanged="eventhandler" />

Examples

Here, a rectangle is placed below a TextBox. When the Input Method Editor (IME) window bounds change, the bottom Margin of the TextBox is increased by the height of the Input Method Editor (IME) candidate window. As a result, the rectangle is pushed down by that amount and is not covered by the candidate window.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <TextBox x:Name="textBox1" Width="300" HorizontalAlignment="Left" 
                 DesiredCandidateWindowAlignment="BottomEdge"
                 CandidateWindowBoundsChanged="OnCandidateWindowBoundsChanged"/>
        <Rectangle Height="100" Width="100" Fill="Red" 
                   HorizontalAlignment="Left"/>
    </StackPanel>
</Grid> 
private void OnCandidateWindowBoundsChanged(TextBox sender, CandidateWindowBoundsChangedEventArgs args) 
{ 
    textBox1.Margin = new Thickness 
    { 
        Left = 0, 
        Top = 0, 
        Right = 0, 
        Bottom = Math.Max(0, args.Bounds.Bottom - textBox1.ActualHeight) 
    }; 
} 

Remarks

For event data, see CandidateWindowBoundsChangedEventArgs.

Users sometimes enter text through an Input Method Editor (IME) that shows in a window just below a text input box (typically for East Asian languages). The Input Method Editor (IME) window can cover important parts of your app UI that the user might need to see while entering text. This event notifies your app of the coordinates where the Input Method Editor (IME) window is currently displayed. You can use this info to draw your UI in a location that doesn't conflict with the Input Method Editor (IME) window.

You can also use the DesiredCandidateWindowAlignment property to specify a preferred placement of the Input Method Editor (IME) window in relation to the text input box.

See Also

ContextMenuOpening ContextMenuOpening ContextMenuOpening ContextMenuOpening

Occurs when the system processes an interaction that displays a context menu.

public : event ContextMenuOpeningEventHandler ContextMenuOpeningpublic event ContextMenuOpeningEventHandler ContextMenuOpeningPublic Event ContextMenuOpening// This API is not available in Javascript.
<TextBox ContextMenuOpening="eventhandler" />

Remarks

To override the context menu, you can handle the ContextMenuOpening event and replace the default menu with a custom menu. For an example of this, see Scenario 2 of the ContextMenu sample. For design info, see Guidelines for context menus.

See Also

CopyingToClipboard CopyingToClipboard CopyingToClipboard CopyingToClipboard

Prerelease. Occurs before copied text is moved to the clipboard.

public : event TypedEventHandler CopyingToClipboard<TextBox,  TextControlCopyingToClipboardEventArgs>public event TypedEventHandler CopyingToClipboard<TextBox,  TextControlCopyingToClipboardEventArgs>Public Event CopyingToClipboard<TextBox,  TextControlCopyingToClipboardEventArgs>// This API is not available in Javascript.
<TextBox CopyingToClipboard="eventhandler"/>

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

CuttingToClipboard CuttingToClipboard CuttingToClipboard CuttingToClipboard

Prerelease. Occurs before cut text is moved to the clipboard.

public : event TypedEventHandler CuttingToClipboard<TextBox,  TextControlCuttingToClipboardEventArgs>public event TypedEventHandler CuttingToClipboard<TextBox,  TextControlCuttingToClipboardEventArgs>Public Event CuttingToClipboard<TextBox,  TextControlCuttingToClipboardEventArgs>// This API is not available in Javascript.
<TextBox CuttingToClipboard="eventhandler"/>

Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.16225.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

Paste Paste Paste Paste

Occurs when text is pasted into the control.

public : event TextControlPasteEventHandler Pastepublic event TextControlPasteEventHandler PastePublic Event Paste// This API is not available in Javascript.
<TextBox Paste="eventhandler"/>

Examples

This example shows how to handle the Paste event to replace line breaks with commas when pasting into an address field. Otherwise, pasting an address copied from multiple lines would cause data loss.

<TextBox Header="Address" Paste="AddressTextBox_Paste"/>
private async void AddressTextBox_Paste(object sender, TextControlPasteEventArgs e)
{
    TextBox addressBox = sender as TextBox;
    if (addressBox != null)
    {
        // Mark the event as handled first. Otherwise, the
        // default paste action will happen, then the custom paste
        // action, and the user will see the text box content change.
        e.Handled = true;

        // Get content from the clipboard.
        var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
        if (dataPackageView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.Text))
        {
            try
            {
                var text = await dataPackageView.GetTextAsync();

                // Remove line breaks from multi-line text and
                // replace with comma(,).
                string singleLineText = text.Replace("\r
", ", "); // Replace any text currently in the text box. addressBox.Text = singleLineText; } catch (Exception) { // Ignore or handle exception as needed. } } } }

This example shows how to handle the Paste event to limit the number of characters pasted into the TextBox. If the length of the text on the clipboard exceeds the MaxLength of the TextBox, a message is shown to the user. The user has the option to continue with the text truncated, or cancel the paste operation.

<TextBox Paste="TextBox_Paste" MaxLength="10"/>
private async void TextBox_Paste(object sender, TextControlPasteEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        // Mark the event as handled first. Otherwise, the
        // default paste action will happen, then the custom paste
        // action, and the user will see the text box content change.
        e.Handled = true;

        // Get content from the clipboard.
        var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
        if (dataPackageView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.Text))
        {
            try
            {
                var text = await dataPackageView.GetTextAsync();
                if (text.Length > tb.MaxLength)
                {
                    // Pasted text is too long. Show a message to the user.
                    // Create the message dialog and set its content
                    var messageDialog = 
                        new Windows.UI.Popups.MessageDialog(
                            "Pasted text excedes maximum allowed (" 
                            + tb.MaxLength.ToString() + 
                            " characters). The text will be truncated.");

                    // Add commands to the message dialog.
                    messageDialog.Commands.Add(new UICommand("Continue", (command) =>
                    {
                        // Truncate the text to be pasted to the MaxLength of the text box.
                        string truncatedText = text.Substring(0, tb.MaxLength);
                        tb.Text = truncatedText;
                    }));
                    messageDialog.Commands.Add(new UICommand("Cancel", (command) =>
                    {
                        // Cancelled. Do nothing.
                    }));

                    // Set the command that will be invoked by default.
                    messageDialog.DefaultCommandIndex = 0;

                    // Set the command to be invoked when escape is pressed.
                    messageDialog.CancelCommandIndex = 1;

                    // Show the message dialog.
                    await messageDialog.ShowAsync();
                }
                else
                {
                    tb.Text = text;
                }                          
            }
            catch (Exception)
            {
                // Ignore or handle exception as needed.
            }
        }
    }
}

Remarks

The Paste event occurs before any content is inserted into the control. You can handle this event to check the contents of the clipboard and perform any actions on the content before it's inserted. If you perform any action, set the Handled property of the event args to true; otherwise, the default paste action is performed. If you mark the event as handled, then it's assumed the app has handled the paste operation, and no default action is performed. You are responsible for determining the insertion point and clipboard content to insert, and inserting the content.

You should set the Handled property to true in your handler before the code to perform a custom paste action. Otherwise, the default paste action is performed, and then the custom action is performed. The user can see the content changing in the TextBox.

SelectionChanged SelectionChanged SelectionChanged SelectionChanged

Occurs when the text selection has changed.

public : event RoutedEventHandler SelectionChangedpublic event RoutedEventHandler SelectionChangedPublic Event SelectionChanged// This API is not available in Javascript.
<TextBox SelectionChanged="eventhandler"/>

TextChanged TextChanged TextChanged TextChanged

Occurs when content changes in the text box.

public : event TextChangedEventHandler TextChangedpublic event TextChangedEventHandler TextChangedPublic Event TextChanged// This API is not available in Javascript.
<TextBox TextChanged="eventhandler"/>

TextChanging TextChanging TextChanging TextChanging

Occurs synchronously when the text in the text box starts to change, but before it is rendered.

public : event TypedEventHandler TextChanging<TextBox,  TextBoxTextChangingEventArgs>public event TypedEventHandler TextChanging<TextBox,  TextBoxTextChangingEventArgs>Public Event TextChanging<TextBox,  TextBoxTextChangingEventArgs>// This API is not available in Javascript.
<TextBox TextChanging="eventhandler"/>

Examples

This example shows how to handle the TextChanging event to implement simple auto-complete for a TextBox.

<!-- Text box in MainPage.xaml -->
<TextBox x:Name="textBox" TextChanging="textBox_TextChanging" 
         Width="200" Height="32"/>
public sealed partial class MainPage : Page
{
    // Boolean to keep track of whether or not you should ignore the next TextChanged event.  
    // This is needed to support the correct behavior when backspace is tapped. 
    public bool m_ignoreNextTextChanged = false;

    // Sample list of strings to use in the autocomplete. 
    public string[] m_options = { "microsoft.com", "dev.windows.com", "msn.com", "office.com", "msdn.microsoft.com" };

    public MainPage()
    {
        this.InitializeComponent();
    }

    private void textBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
    {
        // Needed for the backspace scenario. 
        if (m_ignoreNextTextChanged)
        {
            m_ignoreNextTextChanged = false;
            return;
        }
        // All other scenarios other than the backspace scenario.
        // Do the auto complete. 
        else
        {
            string s = textBox.Text;
            if (s.Length > 0)
            {
                for (int i = 0; i < m_options.Length; i++)
                {
                    if (m_options[i].IndexOf(s) >= 0)
                    {
                        if (s == m_options[i])
                            break;

                        textBox.Text = m_options[i];
                        textBox.Select(s.Length, m_options[i].Length - s.Length);
                        break;
                    }
                }
            }
        }
    }

    protected override void OnKeyDown(KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back
            || e.Key == Windows.System.VirtualKey.Delete)
        {
            m_ignoreNextTextChanged = true;
        }
        base.OnKeyDown(e);
    }
}

Remarks

For event data, see TextBoxTextChangingEventArgs.

The TextChanging event occurs synchronously before the new text is rendered. In contrast, the TextChanged event is asynchronous and occurs after the new text is rendered.

When the TextChanging event occurs, the Text property already reflects the new value (but it's not rendered in the UI). You typically handle this event to update the Text value and selection before the text is rendered. This prevents the text flickering that can happen when text is rendered, updated, and re-rendered rapidly.

Note

This is a synchronous event that can occur at times when changes to the XAML visual tree are not allowed, such as during layout. Therefore, you should limit code within the TextChanging event handler primarily to inspecting and updating the Text property. Attempting to perform other actions, such as showing a popup or adding/removing elements from the visual tree, might cause potentially fatal errors that can lead to a crash. We recommend that you perform these other changes either in a TextChanged event handler, or run them as a separate asynchronous operation.

TextCompositionChanged TextCompositionChanged TextCompositionChanged TextCompositionChanged

Occurs when text being composed through an Input Method Editor (IME) changes.

public : event TypedEventHandler TextCompositionChanged<TextBox,  TextCompositionChangedEventArgs>public event TypedEventHandler TextCompositionChanged<TextBox,  TextCompositionChangedEventArgs>Public Event TextCompositionChanged<TextBox,  TextCompositionChangedEventArgs>// This API is not available in Javascript.
<TextBox TextCompositionChanged="eventhandler"/>

Remarks

For event data, see TextCompositionChangedEventArgs.

This event occurs only when text is composed through an Input Method Editor (IME). Text composition events occur in the following order:

After the TextCompositionStarted event, the TextChanging > TextChanged > TextCompositionChanged event cycle can occur multiple times before the TextCompositionEnded event occurs.

See Also

TextCompositionEnded TextCompositionEnded TextCompositionEnded TextCompositionEnded

Occurs when a user stops composing text through an Input Method Editor (IME).

public : event TypedEventHandler TextCompositionEnded<TextBox,  TextCompositionEndedEventArgs>public event TypedEventHandler TextCompositionEnded<TextBox,  TextCompositionEndedEventArgs>Public Event TextCompositionEnded<TextBox,  TextCompositionEndedEventArgs>// This API is not available in Javascript.
<TextBox TextCompositionEnded="eventhandler"/>

Remarks

For event data, see TextCompositionEndedEventArgs.

This event occurs only when text is composed through an Input Method Editor (IME). Text composition events occur in the following order:

After the TextCompositionStarted event, the TextChanging > TextChanged > TextCompositionChanged event cycle can occur multiple times before the TextCompositionEnded event occurs.

See Also

TextCompositionStarted TextCompositionStarted TextCompositionStarted TextCompositionStarted

Occurs when a user starts composing text through an Input Method Editor (IME).

public : event TypedEventHandler TextCompositionStarted<TextBox,  TextCompositionStartedEventArgs>public event TypedEventHandler TextCompositionStarted<TextBox,  TextCompositionStartedEventArgs>Public Event TextCompositionStarted<TextBox,  TextCompositionStartedEventArgs>// This API is not available in Javascript.
<TextBox TextCompositionStarted="eventhandler"/>

Remarks

For event data, see TextCompositionStartedEventArgs.

This event occurs only when text is composed through an Input Method Editor (IME). Text composition events occur in the following order:

After the TextCompositionStarted event, the TextChanging > TextChanged > TextCompositionChanged event cycle can occur multiple times before the TextCompositionEnded event occurs.

See Also

See Also