TextBox.Paste Événement

Définition

Se produit lorsque du texte est collé dans le contrôle.

public:
 virtual event TextControlPasteEventHandler ^ Paste;
// Register
event_token Paste(TextControlPasteEventHandler const& handler) const;

// Revoke with event_token
void Paste(event_token const* cookie) const;

// Revoke with event_revoker
TextBox::Paste_revoker Paste(auto_revoke_t, TextControlPasteEventHandler const& handler) const;
public event TextControlPasteEventHandler Paste;
function onPaste(eventArgs) { /* Your code */ }
textBox.addEventListener("paste", onPaste);
textBox.removeEventListener("paste", onPaste);
- or -
textBox.onpaste = onPaste;
Public Custom Event Paste As TextControlPasteEventHandler 
<TextBox Paste="eventhandler"/>

Type d'événement

Exemples

Cet exemple montre comment gérer l’événement Paste pour remplacer les sauts de ligne par des virgules lors du collage dans un champ d’adresse. Sinon, le collage d’une adresse copiée à partir de plusieurs lignes entraînerait une perte de données.

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

Cet exemple montre comment gérer l’événement Paste pour limiter le nombre de caractères collés dans textBox. Si la longueur du texte dans le Presse-papiers dépasse la valeur MaxLength du TextBox, un message s’affiche à l’utilisateur. L’utilisateur a la possibilité de continuer avec le texte tronqué ou d’annuler l’opération de collage.

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

Remarques

L’événement Paste se produit avant l’insertion d’un contenu dans le contrôle. Vous pouvez gérer cet événement pour case activée le contenu du Presse-papiers et effectuer des actions sur le contenu avant son insertion. Si vous effectuez une action, définissez la propriété Handled des arguments d’événement sur true ; sinon, l’action de collage par défaut est effectuée. Si vous marquez l’événement comme étant géré, il est supposé que l’application a géré l’opération de collage et qu’aucune action par défaut n’est effectuée. Vous êtes responsable de la détermination du point d’insertion et du contenu du Presse-papiers à insérer, ainsi que de l’insertion du contenu.

Vous devez définir la propriété Handled sur true dans votre gestionnaire avant le code pour effectuer une action de collage personnalisée. Sinon, l’action de collage par défaut est effectuée, puis l’action personnalisée est effectuée. L’utilisateur peut voir le contenu changer dans le TextBox.

S’applique à