[英]WPF textbox derived control override drag&drop OnPreviewDrop (C sharp)
我一直在研究从TextBox派生的自定义控件,遇到了我现在无法解决的问题。 问题的简要描述:我的文本框包含纯文本,其中包含我要保持一致的标签-到目前为止,我已经覆盖了文本选择,因此只能将它们作为整个标签进行选择,等等。现在,我开始进行拖放处理。 如果将任何文本放置在文本字段上,并将其放置在标签上,则我希望插入内容在标签之前或之后移动。 实际的问题在于e.Handled = true的设置。 如果将其设置为true,则几乎可以正常工作-文本是通过我的例程插入的,但不会从源中删除。 如果将其设置为false,则在执行我的方法后,将运行原始文本框的插入方法。 有什么办法可以改变事件路由? 还是我从一开始就解决了这个错误?
我的方法的代码:受保护的重写void 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);
}
}
在OnPreviewDrop处理程序中设置e.Effects可能会产生结果。 我的经验是从源中删除了文本。 设置e.Effects = DragDropEffects.Copy将我的源文本保留下来,这是我想要的行为。 设置e.Handled = true时,DragDropEffects.Move可能会为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.