问题描述
我创建了一个继承 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文本框中粘贴事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!