TextBox TextBox TextBox Class

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

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.

Syntax

Declaration

public class TextBoxpublic class TextBoxPublic Class TextBox
<TextBox .../>

Inheritance Hierarchy

Inherited Members

Inherited properties

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
Tag
Tag
Tag
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Inherited events

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Inherited methods

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Remarks

TextBox 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 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(Int32, Int32) 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 IsSpellCheckEnabledProperty, IsTextPredictionEnabledProperty, and PreventKeyboardDisplayOnProgrammaticFocus. (IsSpellCheckEnabledProperty 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

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 + "!";
}

Constructors summary

Initializes a new instance of the TextBox class.

Properties summary

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

Identifies the AcceptsReturn dependency property.

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

Identifies the DesiredCandidateWindowAlignment dependency property.

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

Identifies the Header dependency property.

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

Identifies the HeaderTemplate dependency property.

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

Identifies the InputScopeProperty dependency property.

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

Identifies the IsColorFontEnabled dependency property.

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

Identifies the IsReadOnly dependency property.

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

Identifies the IsSpellCheckEnabled dependency property.

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

Identifies the IsTextPredictionEnabled dependency property.

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

Identifies the MaxLength dependency property.

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

Identifies the PlaceholderText dependency property.

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

Identifies the PreventKeyboardDisplayOnProgrammaticFocus dependency property.

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

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

Identifies the SelectionHighlightColor dependency property.

Prerelease. Gets or sets the brush used to highlight the selected text when it doesn't have focus.

Prerelease. Identifies the SelectionHighlightColorWhenNotFocused dependency property.

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

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

Gets or sets the text contents of the text box.

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

Identifies the TextAlignment dependency property.

Identifies the Text dependency property.

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

Identifies the TextReadingOrder dependency property.

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

Identifies the TextWrapping dependency property.

Methods summary

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

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

Selects a range of text in the text box.

Selects the entire contents of the text box.

Events summary

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

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

Occurs when text is pasted into the control.

Occurs when the text selection has changed.

Occurs when content changes in the text box.

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

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

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

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

Constructors

  • TextBox()
    TextBox()
    TextBox()
    TextBox()

    Initializes a new instance of the TextBox class.

    public TextBox()public New()Public Sub New()public TextBox()

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 bool AcceptsReturn { get; set; }public bool AcceptsReturn { get; set; }Public ReadWrite Property AcceptsReturn As boolpublic bool AcceptsReturn { get; set; }
    <TextBox AcceptsReturn="bool"/>
    

    Property Value

    • 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 HorizontalScrollBarVisibility or VerticalScrollBarVisibilityProperty 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.

  • 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 DependencyPropertypublic static DependencyProperty AcceptsReturnProperty { get; }

    Property Value

  • 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 CandidateWindowAlignmentpublic CandidateWindowAlignment DesiredCandidateWindowAlignment { get; set; }
    <TextBox DesiredCandidateWindowAlignment="candidateWindowAlignmentMemberName"/>
    

    Property Value

    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 CandidateWindowAlignment 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).

  • 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 DependencyPropertypublic static DependencyProperty DesiredCandidateWindowAlignmentProperty { get; }

    Property Value

  • Header
    Header
    Header
    Header

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

    public object Header { get; set; }public object Header { get; set; }Public ReadWrite Property Header As objectpublic object Header { get; set; }
    <TextBox Header="headerString"/>
    
    

    Property Value

    • 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.

  • 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 DependencyPropertypublic static DependencyProperty HeaderProperty { get; }

    Property Value

  • 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 DataTemplatepublic DataTemplate HeaderTemplate { get; set; }
    <TextBox>
      <TextBox.HeaderTemplate>
        singleDataTemplate
      </TextBox.HeaderTemplate>
    </TextBox>
    

    Property Value

  • 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 DependencyPropertypublic static DependencyProperty HeaderTemplateProperty { get; }

    Property Value

  • 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 InputScopepublic InputScope InputScope { get; set; }
    <TextBox InputScope="inputScopeName" .../>
    

    Property Value

    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 IsSpellCheckEnabledProperty, IsTextPredictionEnabledProperty, and PreventKeyboardDisplayOnProgrammaticFocus. For more info and examples, see Use input scope to change the touch keyboard.

    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;
    
  • InputScopeProperty
    InputScopeProperty
    InputScopeProperty
    InputScopeProperty

    Identifies the InputScopeProperty dependency property.

    public static DependencyProperty InputScopeProperty { get; }public static DependencyProperty InputScopeProperty { get; }Public Static ReadOnly Property InputScopeProperty As DependencyPropertypublic static DependencyProperty InputScopeProperty { get; }

    Property Value

  • 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 bool IsColorFontEnabled { get; set; }public bool IsColorFontEnabled { get; set; }Public ReadWrite Property IsColorFontEnabled As boolpublic bool IsColorFontEnabled { get; set; }
    <TextBox IsColorFontEnabled="bool" />
    

    Property Value

    • 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 DependencyPropertypublic static DependencyProperty IsColorFontEnabledProperty { get; }

    Property Value

  • IsReadOnly
    IsReadOnly
    IsReadOnly
    IsReadOnly

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

    public bool IsReadOnly { get; set; }public bool IsReadOnly { get; set; }Public ReadWrite Property IsReadOnly As boolpublic bool IsReadOnly { get; set; }
    <TextBox IsReadOnly="bool"/>
    

    Property Value

    • 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 IsEnabled is false.

  • 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 DependencyPropertypublic static DependencyProperty IsReadOnlyProperty { get; }

    Property Value

  • IsSpellCheckEnabled
    IsSpellCheckEnabled
    IsSpellCheckEnabled
    IsSpellCheckEnabled

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

    public bool IsSpellCheckEnabled { get; set; }public bool IsSpellCheckEnabled { get; set; }Public ReadWrite Property IsSpellCheckEnabled As boolpublic bool IsSpellCheckEnabled { get; set; }
    <TextBox IsSpellCheckEnabled="bool" />
    

    Property Value

    • 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.

  • 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 DependencyPropertypublic static DependencyProperty IsSpellCheckEnabledProperty { get; }

    Property Value

  • IsTextPredictionEnabled
    IsTextPredictionEnabled
    IsTextPredictionEnabled
    IsTextPredictionEnabled

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

    public bool IsTextPredictionEnabled { get; set; }public bool IsTextPredictionEnabled { get; set; }Public ReadWrite Property IsTextPredictionEnabled As boolpublic bool IsTextPredictionEnabled { get; set; }
    <TextBox IsTextPredictionEnabled="bool" />
    

    Property Value

    • 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 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.

  • 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 DependencyPropertypublic static DependencyProperty IsTextPredictionEnabledProperty { get; }

    Property Value

  • 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 intpublic int MaxLength { get; set; }
    <TextBox MaxLength="int"/>
    

    Property Value

    • 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 DependencyPropertypublic static DependencyProperty MaxLengthProperty { get; }

    Property Value

  • 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 string PlaceholderText { get; set; }public string PlaceholderText { get; set; }Public ReadWrite Property PlaceholderText As stringpublic string PlaceholderText { get; set; }
    <TextBox PlaceholderText="placeholderString"/>
    
    

    Property Value

    • 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 DependencyPropertypublic static DependencyProperty PlaceholderTextProperty { get; }

    Property Value

  • 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 bool PreventKeyboardDisplayOnProgrammaticFocus { get; set; }public bool PreventKeyboardDisplayOnProgrammaticFocus { get; set; }Public ReadWrite Property PreventKeyboardDisplayOnProgrammaticFocus As boolpublic bool PreventKeyboardDisplayOnProgrammaticFocus { get; set; }
    <TextBox PreventKeyboardDisplayOnProgrammaticFocus="bool"/>
    

    Property Value

    • 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 DependencyPropertypublic static DependencyProperty PreventKeyboardDisplayOnProgrammaticFocusProperty { get; }

    Property Value

  • SelectedText
    SelectedText
    SelectedText
    SelectedText

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

    public string SelectedText { get; set; }public string SelectedText { get; set; }Public ReadWrite Property SelectedText As stringpublic string SelectedText { get; set; }
    <TextBox SelectedText="string"/>
    

    Property Value

    • 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 SolidColorBrushpublic SolidColorBrush SelectionHighlightColor { get; set; }
    <TextBox SelectionHighlightColor="{StaticResource resourceName}"/>
    
    

    Property Value

    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.

  • 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 DependencyPropertypublic static DependencyProperty SelectionHighlightColorProperty { get; }

    Property Value

  • SelectionHighlightColorWhenNotFocused
    SelectionHighlightColorWhenNotFocused
    SelectionHighlightColorWhenNotFocused
    SelectionHighlightColorWhenNotFocused

    Prerelease. Gets or sets the brush used to highlight the selected text when it doesn't have focus.

    public SolidColorBrush SelectionHighlightColorWhenNotFocused { get; set; }public SolidColorBrush SelectionHighlightColorWhenNotFocused { get; set; }Public ReadWrite Property SelectionHighlightColorWhenNotFocused As SolidColorBrushpublic SolidColorBrush SelectionHighlightColorWhenNotFocused { get; set; }
    <TextBox SelectionHighlightColorWhenNotFocused="{StaticResource resourceName}"/>
    
    

    Property Value

    • The brush used to highlight the selected text. The default is a null brush from a pure code perspective, but the default control template for TextBox applies a theme resource brush for this in a runtime instance of a TextBox control.

  • SelectionHighlightColorWhenNotFocusedProperty
    SelectionHighlightColorWhenNotFocusedProperty
    SelectionHighlightColorWhenNotFocusedProperty
    SelectionHighlightColorWhenNotFocusedProperty

    Prerelease. Identifies the SelectionHighlightColorWhenNotFocused dependency property.

    public static DependencyProperty SelectionHighlightColorWhenNotFocusedProperty { get; }public static DependencyProperty SelectionHighlightColorWhenNotFocusedProperty { get; }Public Static ReadOnly Property SelectionHighlightColorWhenNotFocusedProperty As DependencyPropertypublic static DependencyProperty SelectionHighlightColorWhenNotFocusedProperty { get; }

    Property Value

  • 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 intpublic int SelectionLength { get; set; }
    <TextBox SelectionLength="int"/>
    

    Property Value

    • 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 intpublic int SelectionStart { get; set; }
    <TextBox SelectionStart="int"/>
    

    Property Value

    • 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 string Text { get; set; }public string Text { get; set; }Public ReadWrite Property Text As stringpublic string Text { get; set; }
    <TextBox Text="string"/>
    

    Property Value

    • 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 TextAlignmentpublic TextAlignment TextAlignment { get; set; }
    <TextBox TextAlignment="textAlignmentMemberName"/>
    

    Property Value

  • 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 DependencyPropertypublic static DependencyProperty TextAlignmentProperty { get; }

    Property Value

  • 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 DependencyPropertypublic static DependencyProperty TextProperty { get; }

    Property Value

  • 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 TextReadingOrderpublic TextReadingOrder TextReadingOrder { get; set; }
    <TextBox TextReadingOrder="textReadingOrderValue"/>
    

    Property Value

    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.

  • 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 DependencyPropertypublic static DependencyProperty TextReadingOrderProperty { get; }

    Property Value

  • 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 TextWrappingpublic TextWrapping TextWrapping { get; set; }
    <TextBlock TextWrapping="Wrap"/>
    -or-
    <TextBlock TextWrapping="NoWrap"/>
    

    Property Value

    Remarks

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

    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>
    
  • 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 DependencyPropertypublic static DependencyProperty TextWrappingProperty { get; }

    Property Value

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<string>> GetLinguisticAlternativesAsync()public IAsyncOperation<IVectorView<string>> GetLinguisticAlternativesAsync()Public Function GetLinguisticAlternativesAsync() As IAsyncOperation( Of IVectorViewstring )public IAsyncOperation<IVectorView<string>> GetLinguisticAlternativesAsync()

    Returns

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

  • 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(Int32 charIndex, Boolean trailingEdge)public Rect GetRectFromCharacterIndex(Int32 charIndex, Boolean trailingEdge)Public Function GetRectFromCharacterIndex(charIndex As Int32, trailingEdge As Boolean) As Rectpublic Rect GetRectFromCharacterIndex(Int32 charIndex, Boolean trailingEdge)

    Parameters

    • charIndex
      System.Int32
      System.Int32
      System.Int32

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

    • trailingEdge
      System.Boolean
      System.Boolean
      System.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.

    Remarks

    To override the context menu, you can handle the ContextMenuOpening event and replace the default menu with a custom menu. Use GetRectFromCharacterIndex(Int32, Boolean) 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.

    Examples

    This example shows how to use GetRectFromCharacterIndex(Int32, Boolean) 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);
    }
    
  • Select(Int32, Int32)
    Select(Int32, Int32)
    Select(Int32, Int32)
    Select(Int32, Int32)

    Selects a range of text in the text box.

    public void Select(Int32 start, Int32 length)public void Select(Int32 start, Int32 length)Public Function Select(start As Int32, length As Int32) As voidpublic void Select(Int32 start, Int32 length)

    Parameters

    • start
      System.Int32
      System.Int32
      System.Int32

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

    • length
      System.Int32
      System.Int32
      System.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 voidpublic void SelectAll()

Events

  • CandidateWindowBoundsChanged
    CandidateWindowBoundsChanged
    CandidateWindowBoundsChanged
    CandidateWindowBoundsChanged

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

    public event TypedEventHandler CandidateWindowBoundsChangedpublic event TypedEventHandler CandidateWindowBoundsChangedPublic Event CandidateWindowBoundsChangedpublic event TypedEventHandler CandidateWindowBoundsChanged
    <TextBox CandidateWindowBoundsChanged="eventhandler" />
    

    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.

    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) 
        }; 
    } 
    
  • ContextMenuOpening
    ContextMenuOpening
    ContextMenuOpening
    ContextMenuOpening

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

    public event ContextMenuOpeningEventHandler ContextMenuOpeningpublic event ContextMenuOpeningEventHandler ContextMenuOpeningPublic Event ContextMenuOpeningpublic event ContextMenuOpeningEventHandler ContextMenuOpening
    <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.

  • Paste
    Paste
    Paste
    Paste

    Occurs when text is pasted into the control.

    public event TextControlPasteEventHandler Pastepublic event TextControlPasteEventHandler PastePublic Event Pastepublic event TextControlPasteEventHandler Paste
    <TextBox Paste="eventhandler"/>
    

    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.

    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\n", ", ");
    
                    // 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.
                }
            }
        }
    }
    
  • SelectionChanged
    SelectionChanged
    SelectionChanged
    SelectionChanged

    Occurs when the text selection has changed.

    public event RoutedEventHandler SelectionChangedpublic event RoutedEventHandler SelectionChangedPublic Event SelectionChangedpublic event RoutedEventHandler SelectionChanged
    <TextBox SelectionChanged="eventhandler"/>
    
  • TextChanged
    TextChanged
    TextChanged
    TextChanged

    Occurs when content changes in the text box.

    public event TextChangedEventHandler TextChangedpublic event TextChangedEventHandler TextChangedPublic Event TextChangedpublic event TextChangedEventHandler TextChanged
    <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 TextChangingpublic event TypedEventHandler TextChangingPublic Event TextChangingpublic event TypedEventHandler TextChanging
    <TextBox TextChanging="eventhandler"/>
    

    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.

    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);
        }
    }
    
  • TextCompositionChanged
    TextCompositionChanged
    TextCompositionChanged
    TextCompositionChanged

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

    public event TypedEventHandler TextCompositionChangedpublic event TypedEventHandler TextCompositionChangedPublic Event TextCompositionChangedpublic event TypedEventHandler TextCompositionChanged

    Remarks

    For event data, see TextCompositionChangedEventArgs.

    This event occurs only when text is composed through an . 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.

  • TextCompositionEnded
    TextCompositionEnded
    TextCompositionEnded
    TextCompositionEnded

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

    public event TypedEventHandler TextCompositionEndedpublic event TypedEventHandler TextCompositionEndedPublic Event TextCompositionEndedpublic event TypedEventHandler TextCompositionEnded

    Remarks

    For event data, see TextCompositionEndedEventArgs.

    This event occurs only when text is composed through an . 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.

  • TextCompositionStarted
    TextCompositionStarted
    TextCompositionStarted
    TextCompositionStarted

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

    public event TypedEventHandler TextCompositionStartedpublic event TypedEventHandler TextCompositionStartedPublic Event TextCompositionStartedpublic event TypedEventHandler TextCompositionStarted

    Remarks

    For event data, see TextCompositionStartedEventArgs.

    This event occurs only when text is composed through an . 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.

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ComposableAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute

Details

Assembly

Windows.UI.Xaml.Controls.dll