Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

Wpf: Drag And Drop To A Textbox

I've googled this problem, and people have answered similar questions, but for some reason I can't get anything to work. I must have missed something here... At any rate, when I run the following code, the TextBox_DragEnter handler is never called. However, if I change the TextBox element in the xaml to a TextBlock element, it is called. Is there any way to get the same behavior from a TextBox element? The following code completely isolates the problem...

MainWindow.xaml:

<Window x:Class="Wpf1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="myGrid">
        <TextBox AllowDrop="True" PreviewDragEnter="TextBox_DragEnter" PreviewDrop="TextBox_Drop" />
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Collections.ObjectModel;

namespace Wpf1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextBox_DragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
        }

        private void TextBox_Drop(object sender, DragEventArgs e)
        {

        }
    }
}

Many thanks in advance!

Andrew

EDIT:

Just to clarify, I would like to allow dropping a custom object into a textbox. In the Drop handler for the textbox, I would then like to set the text of the textbox to a property in the object, and then set the IsReadOnly property of the TextBox to false. I'm just having some trouble enabling drag and drop for the TextBox...

question from:https://stackoverflow.com/questions/4281857/wpf-drag-and-drop-to-a-textbox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you add a handler for PreviewDragOver, then set e.Handled = true it should work.

Works for me in any case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...