2013-07-26 153 views
3

基本上我通过拖放标签到文本框来拖放使用文本框和标签。文本框和标签在循环中创建。WPF C#拖放

我已动态创建文本框(文本框是放置目标)是这样的:

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()); 

      } 

我也dynanmically创建标签(标签拖动目标)是这样的:

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); 
     } 

我这里有两个问题。

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

这里是我的代码:

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

其次,我也希望在拖动目标被丢弃,因为我可能有其他的阻力目标投进TBOX之前清除tbox.Text。所以我想清除tbox.Text并拖动拖动目标每当我拖动目标文本框。

我该怎么做?我被困在哪个事件我应该使用这个,我如何从这些事件处理程序访问Tbox?

+0

你可以显示你在做什么鼠标下降事件? – Nitesh

回答

2

它为我工作。

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

,如果你使用的是他们只是将目的你不需要为LabelMouseMoveDragEnter事件。

更换Drop事件与PreviewDropTextBox,如下图所示:

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; 
} 
+0

感谢您的快速回复和努力 – user2376998

+0

这也是一个很好的例子:https://wpf.2000things.com/2013/01/09/730-use-querycontinuedrag-event-to-know-when -mouse-按钮状态-更改/ – AzzamAziz

0

要拖动文本框(添加鼠标按下事件)

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); 
     } 

的您想放置的TextBox(添加放置e通风口,你也必须检查标记为允许复选框)

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; 
}