如何动态更改将在TextBox中粘贴的内容.
以下是我订阅活动的方式:
DataObject.AddPastingHandler (uiTextBox, TextBoxPaste);
Run Code Online (Sandbox Code Playgroud)
以下是我定义事件处理程序的方法:
private void TextBoxPaste (object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData (typeof (string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (@"\D");
string result = nonNumeric.Replace (clipboard, String.Empty);
// I can't just do "args.DataObject.SetData (result)" here.
}
Run Code Online (Sandbox Code Playgroud)
Far*_*win 28
因为DataObject被冻结,所以不能调用args.DataObject.SetData("some data").你可以做的是完全替换DataObject:
private void TextBoxPaste(object sender, DataObjectPastingEventArgs e) {
string text = (String)e.DataObject.GetData(typeof(String));
DataObject d = new DataObject();
d.SetData(DataFormats.Text, text.Replace(Environment.NewLine, " "));
e.DataObject = d;
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*lad 17
我可以想到两种方式,其中没有一种非常有吸引力:)两种方式都包括取消粘贴命令.
第一种方法是取消粘贴命令,然后计算粘贴后粘贴后文本的样子result.
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
int start = uiTextBox.SelectionStart;
int length = uiTextBox.SelectionLength;
int caret = uiTextBox.CaretIndex;
string text = uiTextBox.Text.Substring(0, start);
text += uiTextBox.Text.Substring(start + length);
string newText = text.Substring(0, uiTextBox.CaretIndex) + result;
newText += text.Substring(caret);
uiTextBox.Text = newText;
uiTextBox.CaretIndex = caret + result.Length;
args.CancelCommand();
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是取消粘贴命令,更改剪贴板中的文本,然后重新执行粘贴.这还需要您在实际粘贴命令和手动调用粘贴命令之间有所不同.像这样的东西
bool m_modifiedPaste = false;
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
if (m_modifiedPaste == false)
{
m_modifiedPaste = true;
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
args.CancelCommand();
Clipboard.SetData(DataFormats.Text, result);
ApplicationCommands.Paste.Execute(result, uiTextBox);
}
else
{
m_modifiedPaste = false;
}
}
Run Code Online (Sandbox Code Playgroud)