5

基本上我通过将标签拖到文本框来使用文本框和标签进行拖放。文本框和标签在相同的 for 循环中创建。

我已经动态创建了文本框(文本框是放置目标),如下所示:

  TextBox tbox = new TextBox();
            tbox.Width = 250;
            tbox.Height = 50;
            tbox.AllowDrop = true;
            tbox.FontSize = 24;
            tbox.BorderThickness = new Thickness(2);
            tbox.BorderBrush = Brushes.BlanchedAlmond;     
            tbox.Drop += new DragEventHandler(tbox_Drop);

            if (lstQuestion[i].Answer.Trim().Length > 0)
            {

                wrapPanel2.Children.Add(tbox);
                answers.Add(lbl.Content.ToString());
                MatchWords.Add(question.Content.ToString(), lbl.Content.ToString()); 

            }

我还像这样动态创建标签(标签是拖动目标):

  Dictionary<string, string> shuffled = Shuffle(MatchWords);
        foreach (KeyValuePair<string, string> s in shuffled)
        {
            Label lbl = new Label();
            lbl.Content = s.Value;
            lbl.Width = 100;
            lbl.Height = 50;
            lbl.FontSize = 24;              
            lbl.DragEnter += new DragEventHandler(lbl_DragEnter);
            lbl.MouseMove += new MouseEventHandler(lbl_MouseMove);
            lbl.MouseDown +=new MouseButtonEventHandler(lbl_MouseDown);
     //       lbl.MouseUp +=new MouseButtonEventHandler(lbl_MouseUp);
           dockPanel1.Children.Add(lbl);
        }

我这里有 2 个问题。

第一个。我正在使用 tbox.drop 事件来显示 MessageBox.Show(something) ;在拖放目标时显示消息框,但它不起作用。

这是我的代码:

       private void tbox_Drop(object sender, DragEventArgs e)
    {
        MessageBox.Show("Are you sure?");
    }

其次,我还想在拖放目标时清除 tbox.Text,因为我之前可能将其他拖动目标拖放到 tbox 中。所以我想每次将目标拖动到文本框时清除 tbox.Text 并放下拖动目标。

我怎么做?我被困在我应该为此使用哪个事件以及如何从这些事件处理程序访问 tbox ?

4

2 回答 2

4

它对我有用。

private void lbl_MouseDown(object sender, MouseButtonEventArgs e)
{
    Label _lbl = sender as Label;
    DragDrop.DoDragDrop(_lbl, _lbl.Content, DragDropEffects.Move);
}

如果您仅将它们用于拖动目的,则不需要MouseMoveDragEnter事件。Label

Dropevent替换PreviewDrop为 for TextBox,如下所示:

tbox.Drop += new DragEventHandler(tbox_Drop);

有了这个

tbox.PreviewDrop += new DragEventHandler(tbox_PreviewDrop);

private void tbox_PreviewDrop(object sender, DragEventArgs e)
{
    (sender as TextBox).Text = string.Empty;
}
于 2013-07-26T04:22:46.610 回答
0

要拖动的文本框(添加 mousedown 事件)

private void dragMe_MouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox tb = sender as TextBox;
            // here we have pass the textbox object so that we can use its all property on necessary
            DragDrop.DoDragDrop(tb, tb, DragDropEffects.Move);
        }

您要放置的文本框(添加放置事件,并且您必须选中标记为 allowdrop 复选框)

 private void dropOnMe_Drop(object sender, DragEventArgs e)
 {

            TextBox tb= e.Data.GetData(typeof(TextBox)) as TextBox;
            // we have shown the content of the drop textbox(you can have any property on necessity)
            dropOnMe.Content = tb.Content;
 }
于 2015-09-02T11:31:30.920 回答