WPF也可以拖放C#拖动图像

时间:2013-07-15 01:28:20

标签: c# wpf drag-and-drop

我动态填充停靠面板,其中包含来自数据库和另一个停靠面板的答案以及来自数据库的问题。答案将填充为标签,我试图拖放标签到文本块。是的我可以拖放,但问题是我也想拖动标签。例如,如果Label内容是Hello,我希望用“hello”这个词拖动你好,现在,当我拖动它时,它也不会拖动单词,但当我将它放入一个文本框,删除了“你好”这个词。我想将动画或单词与光标一起拖动。

这是我的代码:

        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
    }

2 个答案:

答案 0 :(得分:1)

您可以按照以下链接中列出的策略进行操作,该策略基本上会创建一个新窗口,并使用鼠标光标更新窗口位置。

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

所以页面的主要部分是你使用Adorner装饰光标。

您可以在DragSource事件处理程序上使用this.DragSource.GiveFeedback和其他事件来设置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

答案 1 :(得分:0)

看看这个 http://blogs.msdn.com/b/adamroot/archive/2008/02/19/shell-style-drag-and-drop-in-net-wpf-and-winforms.aspx

默认的wpf拖放&amp; drop的动画很难看,如果你想在拖动时显示一些文字或图像,你需要 做更多的事情。