在 WPF 文本框中粘贴事件 [英] Paste Event in a WPF TextBox

查看:32
本文介绍了在 WPF 文本框中粘贴事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个继承 TextBox 的自定义控件.这个自定义控件是一个数字TextBox,只支持数字.

I have created a custom control inheriting TextBox. This custom control is a numeric TextBox, only supporting numbers.

我正在使用 OnPreviewTextInput 检查输入的每个新字符以查看该字符是否为有效输入.这很好用.但是,如果我将文本粘贴到 TextBox 中,则不会触发 OnPreviewTextInput.

I am using OnPreviewTextInput to check each new character being typed to see if the character is a valid input. This works great. However, if I paste the text into the TextBox, OnPreviewTextInput is not fired.

TextBox 中捕获粘贴文本的最佳方法是什么?

What is the best way to capture pasted text in a TextBox?

另外,我在按下退格键时遇到问题,我不知道这会触发什么事件.OnPreviewTextInput 没有被触发!

Also, I have a problem when the back space is pressed, I can't figure out what event this will fire. OnPreviewTextInput is not fired!

任何想法如何在 WPF TextBox 中捕获粘贴的文本和退格事件?

Any ideas how to capture pasted text and back space events in WPF TextBox?

推荐答案

这里有一些代码,以防我需要它.可能对你有帮助.

Here's some code I had lying around in case I ever needed it. Might help you.

public Window1()
{
    InitializeComponent();

    // "tb" is a TextBox
    DataObject.AddPastingHandler(tb, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
    if (!isText) return;

    var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
    ...
}

这篇关于在 WPF 文本框中粘贴事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆