【发布时间】:2010-12-17 14:04:31
【问题描述】:
我一直在处理从 TextBox 派生的自定义控件,但遇到了一个我现在无法解决的问题。问题的简要描述:我的文本框包含纯文本,其中包含我想要保持一致的标签 - 到目前为止,我已经覆盖了文本选择,因此它们只能作为整个标签等选择。 现在我已经开始处理拖放了。如果将任何文本放在文本字段上并将其放在标签上,我希望将插入移动到标签之前或之后。实际问题在于 e.Handled=true 的设置。如果我将它设置为 true,它几乎可以工作 - 文本是通过我的例程插入的,但它不会从源中删除。如果我将其设置为 false,则在执行我的方法后,将运行原始文本框的插入方法。有没有办法改变事件路由?还是我从一开始就犯了这个错误?
我的方法代码: 受保护的覆盖无效 OnPreviewDragEnter(DragEventArgs e) { base.OnPreviewDragEnter(e); e.Handled = true; // 让我们画出我们自己的插入符号... }
protected override void OnPreviewDrop(DragEventArgs e)
{
base.OnPreviewDrop(e);
fieldsReady = false;
int selStart = this.SelectionStart;
int selLength = this.SelectionLength;
string droppedData = (string)e.Data.GetData(DataFormats.StringFormat);
// where to insert
Point whereDropped = e.GetPosition(this);
int droppedIndex = GetCharacterIndexFromPoint(whereDropped, true);
if (droppedIndex == this.Text.Length - 1)
{
double c = GetRectFromCharacterIndex(droppedIndex).X;
if (whereDropped.X > c)
droppedIndex++;
}
// only if the source was us, do this:
if (this.SelectionLength > 0) // this means that we are dragging from our textbox!
{
// was there any selection? if so, remove it!
this.Text = this.Text.Substring(0, selStart) + this.Text.Substring(selStart + selLength);
e.Handled = true;
// 2DO!! alter the indices depending on the removed selection
// insertion
this.Text = this.Text.Substring(0, droppedIndex) + droppedData + this.Text.Substring(droppedIndex);
}
}
【问题讨论】:
标签: c# textbox drag-and-drop