简体   繁体   中英

WPF - How to disable drag and drop WITHIN a textbox control?

If you look at how textboxes appear in Windows Explorer - if you rename a file it highlights the entire text. But if you drag to select text, it will change the selection to fit the user's drag.

In WPF, if you select all the text of a textbox, then drag in the text area to select text, it will try and drag & drop the text within the textbox area. I was wondering if there was a way in WPF to disable this functionality, to have it more like Windows Explorer?

It's needed mostly because when people rename things they either want to rename the whole thing (backspace after activating a rename, since all the text is highlighted) or part of it (user drags to highlight some text.) Windows Explorer combines both and it works very well, and I'd need to duplicate that functionality in WPF.

You can use DataObject.AddCopyingHandler :

DataObject.AddCopyingHandler(textbox, (s, e) =>
{
    if (e.IsDragDrop) e.CancelCommand();
});

EDIT:

when dragging to select text it doesn't set the cursor position as the beginning of the selection, it just uses the beginning of the text in the textbox

You can drop the current selection, right before actually selecting it :

textbox.PreviewMouseLeftButtonDown += (s, e) =>
{
    textbox.Select(0, 0);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM