我已经创建了一个继承TextBox
的自定义控件。此自定义控件是一个数字TextBox
,仅支持数字。
我使用OnPreviewTextInput
检查每个正在键入的新字符,以查看该字符是否为有效输入。这很好用。但是,如果我将文本粘贴到TextBox
中,则不会触发OnPreviewTextInput
。
在TextBox
中捕获粘贴文本的最佳方法是什么
此外,我还有一个问题,当后退空间被按下时,我不能确定这将触发什么事件。OnPreviewTextInput
没有被解雇!
如何在WPF TextBox
中捕获粘贴的文本和退格键事件
发布于 2010-06-17 20:15:49
这里有一些我放在那里的代码,以备不时之需。可能会对你有帮助。
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;
...
}
发布于 2010-06-17 20:13:04
对于退格键,请检查PreviewKeyDown事件
对于粘贴命令,将命令绑定添加到ApplicationCommands.Paste,并将参数设置为handled (如果不希望对其执行任何操作):
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
Executed="PasteExecuted" />
</Window.CommandBindings>
在后面的代码中:
private void PasteExecuted(object sender, ExecutedRoutedEventArgs e)
{
e.Handled = true;
}
发布于 2019-12-03 15:45:06
这可能不是你想要的确切答案,但这里是如何处理粘贴的文本(如果用户使用上下文菜单粘贴,这也适用):
InitializeComponent();
// "DescriptionTextBox" is a TextBox
DataObject.AddPastingHandler(DescriptionTextBox, OnDescriptionPaste);
private void OnDescriptionPaste(object sender, DataObjectPastingEventArgs e)
{
if (!e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true))
return;
var pastedText = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
if (string.IsNullOrEmpty(pastedText))
return;
var txtBox = (TextBox) sender;
var before = ""; //Text before pasted text
var after = txtBox.Text; //Text after pasted text
//Get before and after text
if (txtBox.CaretIndex > 0)
{
before = txtBox.Text.Substring(0, txtBox.CaretIndex);
after = txtBox.Text.Substring(txtBox.CaretIndex);
}
//Do custom logic for handling the pasted text.
//Split sentences ending with . into new line.
var parts = pastedText.Split(new []{'.'}, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
pastedText = parts.Select(x => x.Trim()).ToArray().ToStringX(".\r\n");
pastedText += ".";
}
var newCaretIndex = before.Length + pastedText.Length;
e.CancelCommand(); //Cancels the paste, we do it manually
txtBox.Text = $"{before}{pastedText}{after}"; //Set new text
txtBox.CaretIndex = newCaretIndex; //Set new caret index
}
为了处理退格键,使用PreviewKeyDown事件。
https://stackoverflow.com/questions/3061475
复制相似问题