2013-07-15 166 views
0

我動態填充一個停靠面板與來自數據庫的問題從數據庫和另一個停靠面板的答案以及。答案將填充爲標籤,我試圖拖放標籤到文本塊。是的,我可以拖放,但事情是我想拖動標籤。例如,如果Label內容是Hello,我希望hello被單詞「hello」拖動,現在,當我拖動它時,它也不會拖動單詞,但是當我將它放入一個文本框,單詞「你好」被刪除。我想要將動畫或單詞與光標一起拖動。WPF拖放C#拖動圖像以及

這是我的代碼:

 private void PopulateQuestion(int activityID, int taskID) 
    { 
     IList<Model.question> lstQuestion = qn.GetRecords(taskID, activityID); 
     StackPanel sp = new StackPanel(); 
     StackPanel stp = new StackPanel(); 
     foreach (Model.question qhm in lstQuestion) 
     { 

      StackPanel sp1 = new StackPanel() { Orientation = Orientation.Horizontal }; // Question 
      TextBlock tb = new TextBlock(); 
      tb.Text = qhm.QuestionContent; 
      tb.FontWeight = FontWeights.Bold; 
      tb.FontSize = 24; 
      sp1.Children.Add(tb); 

      StackPanel sp2 = new StackPanel() { Orientation = Orientation.Horizontal }; // Answer 
      Label tb1 = new Label(); 
      tb1.Content = qhm.Answer; 
      tb1.FontWeight = FontWeights.Bold; 
      tb1.FontSize = 24; 
      tb1.MouseLeftButtonDown += tb1_Click; 
      sp2.Children.Add(tb1); 

      TextBox tbox = new TextBox(); 
      tbox.Width = 100; 
      tbox.FontSize = 24; 
      tbox.AllowDrop = true; 
      tbox.FontWeight = FontWeights.Bold; 

      if (qhm.Answer.Trim().Length > 0) 
      { 

       sp1.Children.Add(tbox); 

      } 

      sp.Children.Add(sp1); 
      stp.Children.Add(sp2); 
     } 

     dockQuestion.Children.Add(sp); 
     dockAnswer.Children.Add(stp); 
    } 

    private void tb1_Click(object sender, RoutedEventArgs e) 
    { 
     Label lbl = (Label)sender; 
     DataObject dataObj = new DataObject(lbl.Content); 
     DragDrop.DoDragDrop(lbl, dataObj, DragDropEffects.All); 

     lbl.IsEnabled = false; 
     lbl.Foreground = (SolidColorBrush)new BrushConverter().ConvertFromString("#FFFB3B46"); // Red 
    } 

回答

1

你可以按照下面的鏈接,它本質上創建了一個新的窗口,並導致鼠標光標被更新的窗口位置勾畫的戰略。

http://blogs.msdn.com/b/jaimer/archive/2007/07/12/drag-drop-in-wpf-explained-end-to-end.aspx

因此,從頁面的要點是你裝飾用的裝飾器光標。

您可以使用this.DragSource.GiveFeedback和DragSource事件處理程序上的其他事件來設置Adorner。

一旦你有了事件處理程序,那就給了你做某事的機會。

//Here we create our adorner.. 
_adorner = new DragAdorner(DragScope, (UIElement)this.dragElement, true, 0.5); 
_layer = AdornerLayer.GetAdornerLayer(DragScope as Visual); 
_layer.Add(_adorner); 

所以你可以創建自己的Adorner的子類。您在這裏可以找到創建自定義裝飾器的詳細信息:

http://msdn.microsoft.com/en-us/library/ms743737.aspx

+0

嗨,那裏,謝謝你的鏈接,但我幾乎不能理解它,新的這.... – user2376998

+0

感謝您的時間。我仍然困惑,但我想我會創建一個任何事件處理程序,並在其中做裝飾者?或者我需要使用mousedown事件來查找鼠標光標的位置? – user2376998

+0

從源代碼的開始部分看起來像添加鼠標事件處理程序作爲第一步:this.DragSource.PreviewMouseLeftButtonDown和this.DragSource.PreviewMouseMove – Ted