2013-07-26 156 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; 
}