Beispiel #1
0
        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsEnabled && CheckIsValidDrag() && _start.HasValue)
            {
                //Point mpos = e.GetPosition(null);
                var mp = new POINT();
                GetCursorPos(ref mp);
                var    mpos = new Point(mp.X, mp.Y);
                Vector diff = _start.Value - mpos;

                if (e.LeftButton == MouseButtonState.Pressed &&
                    Math.Abs(diff.X) > AppSettings.MinimumHorizontalDragDistance ||
                    Math.Abs(diff.Y) > AppSettings.MinimumVerticalDragDistance)
                {
                    _start = null;

                    if (AssociatedObject is IAnimatableElement ae)
                    {
                        ae.WidthBackup  = AssociatedObject.ActualWidth;
                        ae.HeightBackup = AssociatedObject.ActualHeight;
                    }

                    DragDropAnimation?.Start(AssociatedObject, BeginDragEffectAnimationName);
                    AssociatedObject.GiveFeedback += AssociatedObject_GiveFeedback;

#if alldbg || dbg
                    DesktopPanelTool.Lib.Debug.WriteLine($"do drag drop (mpos={mpos}) (diff.X={diff.X} diff.Y={diff.Y})");
#endif
                    _dataObject = new DataObject(AssociatedObject.GetType(), AssociatedObject);
                    var r = DragDrop.DoDragDrop(AssociatedObject, _dataObject, DragDropEffects.Move);

                    var p = new POINT();
                    GetCursorPos(ref p);
                    AssociatedObject.GiveFeedback -= AssociatedObject_GiveFeedback;
                    var dropAcceptedInApp     = r != DragDropEffects.None;
                    var dropAcceptedOnDesktop = CanDropOnDesktop && (!dropAcceptedInApp && CheckIsOverDesktop(p.X, p.Y));
                    var dropAccepted          = dropAcceptedInApp | dropAcceptedOnDesktop;

                    if (!dropAccepted)
                    {
                        DragDropAnimation?.Start(_cursorWindow, CancelDragEffectAnimationName, null, (o, e) => DestroyCursorWindow());
                    }

                    if (!dropAcceptedOnDesktop)
                    {
                        DragDropAnimation?.Start(AssociatedObject, EndDragEffectAnimationName);
                    }

                    if (DragDropAnimation == null || dropAccepted)
                    {
                        DestroyCursorWindow();
                    }

                    if (dropAcceptedOnDesktop && DropOnDesktopHandlerCommand != null)
                    {
                        var dragComponentData = new DragData(_dataObject, null, AssociatedObject);
                        if (DropOnDesktopHandlerCommand.CanExecute(dragComponentData))
                        {
                            DropOnDesktopHandlerCommand.Execute(dragComponentData);
                        }
                        DragDropAnimation?.Start(AssociatedObject, EndDragEffectAnimationName);
                    }
                }
            }
        }
Beispiel #2
0
        private void TreeView_After_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    UIElement element       = e.OriginalSource as UIElement;
                    bool      bGridSplitter = CheckGridSplitter(element);


                    Point currentPosition = e.GetPosition(TreeView_After);

                    double movedX = 0, movedY = 0;
                    if (!((_lastMouseDown.X == -1) && (_lastMouseDown.Y == -1)))
                    {
                        movedX = Math.Abs(currentPosition.X - _lastMouseDown.X);
                        movedY = Math.Abs(currentPosition.Y - _lastMouseDown.Y);
                    }

                    if ((movedX > const_DragMoveDist) ||
                        (movedY > const_DragMoveDist))
                    {
                        //draggedItem = (Tasks.TaskNodeViewModel)TreeView_After.SelectedItem;
                        if (NVM_TreeView_After_selectedItems.Count > 0)
                        {
                            draggedItems = new List <Tasks.TaskNodeViewModel>();
                            foreach (Tasks.TaskNodeViewModel vm in NVM_TreeView_After_selectedItems.Keys)
                            {
                                draggedItems.Add(vm);
                            }
                        }
                        else
                        {
                            draggedItems = null;
                        }

                        if ((draggedItems != null) && !bGridSplitter)
                        {
                            DragDropEffects finalDropEffect = DragDrop.DoDragDrop(TreeView_After, TreeView_After.SelectedValue,
                                                                                  DragDropEffects.Move);
                            //Checking target is not null and item is dragging(moving)
                            if ((finalDropEffect == DragDropEffects.Move) && (_target != null))
                            {
                                // A Move drop was accepted

                                /*
                                 * bool Correct_drop = true;
                                 * foreach( Tasks.TaskNodeViewModel vm in draggedItems )
                                 *  if(vm.Name == _target.Name)
                                 *      Correct_drop = false;
                                 */

                                //private bool CheckDropTarget(List<Tasks.TaskNodeViewModel> _sourceItems, Tasks.TaskNodeViewModel _targetItem)


                                if (CheckDropTarget(draggedItems, _target))
                                {
                                    MoveItem(draggedItems, _target);
                                    _target      = null;
                                    draggedItems = null;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("TaskView MouseMove: " + ex.Message);

                draggedItems = null;
            }
        }
        void StartDrag()
        {
            // prevent nested StartDrag calls
            mode = SelectionMode.Drag;

            // mouse capture and Drag'n'Drop doesn't mix
            textArea.ReleaseMouseCapture();

            DataObject dataObject = textArea.Selection.CreateDataObject(textArea);

            DragDropEffects allowedEffects = DragDropEffects.All;
            var             deleteOnMove   = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();

            foreach (ISegment s in deleteOnMove)
            {
                ISegment[] result = textArea.GetDeletableSegments(s);
                if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset)
                {
                    allowedEffects &= ~DragDropEffects.Move;
                }
            }

            var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);

            textArea.RaiseEvent(copyingEventArgs);
            if (copyingEventArgs.CommandCancelled)
            {
                return;
            }

            object dragDescriptor = new object();

            this.currentDragDescriptor = dragDescriptor;

            DragDropEffects resultEffect;

            using (textArea.AllowCaretOutsideSelection()) {
                var oldCaretPosition = textArea.Caret.Position;
                try {
                    Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
                    resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
                    Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
                } catch (COMException ex) {
                    // ignore COM errors - don't crash on badly implemented drop targets
                    Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
                    return;
                }
                if (resultEffect == DragDropEffects.None)
                {
                    // reset caret if drag was aborted
                    textArea.Caret.Position = oldCaretPosition;
                }
            }

            this.currentDragDescriptor = null;

            if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move)
            {
                bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
                if (draggedInsideSingleDocument)
                {
                    textArea.Document.UndoStack.StartContinuedUndoGroup(null);
                }
                textArea.Document.BeginUpdate();
                try {
                    foreach (ISegment s in deleteOnMove)
                    {
                        textArea.Document.Remove(s.Offset, s.Length);
                    }
                } finally {
                    textArea.Document.EndUpdate();
                    if (draggedInsideSingleDocument)
                    {
                        textArea.Document.UndoStack.EndUndoGroup();
                    }
                }
            }
        }
Beispiel #4
0
 private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     DropImage = (DropImage)ListBox1.SelectedItem;
     DragDrop.DoDragDrop(ListBox1, DropImage.Text, DragDropEffects.Copy);
 }
Beispiel #5
0
 private void rorigin_MouseDown(object sender, MouseButtonEventArgs e)
 {
     DragDrop.DoDragDrop(this.rorigin, sender, DragDropEffects.Move);
 }
Beispiel #6
0
 public override void StartDrag(DependencyObject dragSource, SharpTreeNode[] nodes)
 {
     DragDrop.DoDragDrop(dragSource, Copy(nodes), DragDropEffects.All);
 }
Beispiel #7
0
 private void DragDo(DragContent dragData)
 {
     DragDrop.DoDragDrop(TreeView, new DataObject(dragData), DragDropEffects.All);
 }
Beispiel #8
0
        private void btnFile_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (file == null)
            {
                return;
            }

            if (!file.IsFileSystem)
            {
                // we can only perform file operations on filesystem objects
                return;
            }

            if (!IsRenaming)
            {
                if (!inDrag && startPoint != null)
                {
                    inDrag = true;

                    Point mousePos = e.GetPosition(this);

                    if (mousePos.X == 0 && mousePos.Y == 0)
                    {
                        // sometimes we get an invalid position, ignore it so we don't start a drag operation
                        startPoint = null;
                        return;
                    }

                    Vector diff = (Point)startPoint - mousePos;

                    if (mousePos.Y <= ActualHeight && ((Point)startPoint).Y <= ActualHeight &&
                        (e.LeftButton == MouseButtonState.Pressed || e.RightButton == MouseButtonState.Pressed) &&
                        (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                         Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
                    {
                        Button     button     = sender as Button;
                        DataObject dragObject = new DataObject();

                        try
                        {
                            dragObject.SetFileDropList(
                                new System.Collections.Specialized.StringCollection {
                                file.Path
                            });

                            DragDrop.DoDragDrop(button, dragObject,
                                                (e.RightButton == MouseButtonState.Pressed
                                    ? DragDropEffects.All
                                    : DragDropEffects.Move));
                        }
                        catch (Exception exception)
                        {
                            ShellLogger.Warning($"Icon: Unable to perform drag-drop operation: {exception.Message}");
                        }

                        // reset the stored mouse position
                        startPoint = null;
                    }
                    else if (e.LeftButton != MouseButtonState.Pressed && e.RightButton != MouseButtonState.Pressed)
                    {
                        // reset the stored mouse position
                        startPoint = null;
                    }

                    inDrag = false;
                }

                e.Handled = true;
            }
        }
        public DADQuestion()
        {
            InitializeComponent();
            TTimer = new Timer(
                new TimerCallback(NextQuestion),
                null,
                50000,
                50000);
            userImage.Source = new BitmapImage(new Uri(Gradinita.currentUser.ImgSource));
            nr1.Source       = new BitmapImage(new Uri(Gradinita.dirSource + "cf8.png"));
            //Gradinita.OrdoneazaNumerele.Play();

            nr1.MouseLeftButtonDown += (s, e) =>
            {
                Image img = s as Image;

                DataObject data = new DataObject(DataFormats.Text, img.Source);

                DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
            };
            nr1.Height = 150;
            nr1.Width  = 150;
            nr2.Source = new BitmapImage(new Uri(Gradinita.dirSource + "cf1.png"));
            nr2.MouseLeftButtonDown += (s, e) =>
            {
                Image img = s as Image;

                DataObject data = new DataObject(DataFormats.Text, img.Source);

                DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
            };
            nr2.Height = 150;
            nr2.Width  = 150;
            nr3.Source = new BitmapImage(new Uri(Gradinita.dirSource + "cf6.png"));
            nr3.MouseLeftButtonDown += (s, e) =>
            {
                Image img = s as Image;

                DataObject data = new DataObject(DataFormats.Text, img.Source);

                DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
            };
            nr3.Height  = 150;
            nr3.Width   = 150;
            img1.Source = new BitmapImage(new Uri(Gradinita.dirSource + "plh.png"));
            img1.Drop  += (s, e) =>
            {
                Image       img    = e.Source as Image;
                BitmapImage source = (BitmapImage)e.Data.GetData(DataFormats.Text);

                if (source.UriSource.AbsolutePath == Gradinita.dirSource + "cf1.png")
                {
                    img.Source = source;
                    cnt++;
                    if (cnt == 3)
                    {
                        TTimer.Dispose();
                        Thread.Sleep(1000);
                        Gradinita.currentUser.Score += score - wrongAnswers;
                        TestGradinita.Gradinita.CorrectAnswerSound.Play();
                        Thread.Sleep(3000);
                        this.NavigationService.Navigate(new QuestionPage());
                    }
                }
                else
                {
                    wrongAnswers++;
                    Gradinita.WrongAnswerSound.Play();
                }
            };
            img1.Height = 150;
            img1.Width  = 150;
            img2.Source = new BitmapImage(new Uri(Gradinita.dirSource + "plh.png"));
            img2.Drop  += (s, e) =>
            {
                Image       img    = e.Source as Image;
                BitmapImage source = (BitmapImage)e.Data.GetData(DataFormats.Text);

                if (source.UriSource.AbsolutePath == Gradinita.dirSource + "cf6.png")
                {
                    img.Source = source;
                    cnt++;
                    if (cnt == 3)
                    {
                        TTimer.Dispose();
                        Gradinita.currentUser.Score += score - wrongAnswers;
                        TestGradinita.Gradinita.CorrectAnswerSound.Play();
                        Thread.Sleep(3000);
                        this.NavigationService.Navigate(new QuestionPage());
                    }
                }
                else
                {
                    wrongAnswers++;
                    Gradinita.WrongAnswerSound.Play();
                }
            };
            img2.Height = 150;
            img2.Width  = 150;
            img3.Source = new BitmapImage(new Uri(Gradinita.dirSource + "plh.png"));
            img3.Drop  += (s, e) =>
            {
                Image       img    = e.Source as Image;
                BitmapImage source = (BitmapImage)e.Data.GetData(DataFormats.Text);

                if (source.UriSource.AbsolutePath == Gradinita.dirSource + "cf8.png")
                {
                    img.Source = source;
                    cnt++;
                    if (cnt == 3)
                    {
                        TTimer.Dispose();
                        Gradinita.currentUser.Score += score - wrongAnswers;
                        TestGradinita.Gradinita.CorrectAnswerSound.Play();
                        Thread.Sleep(3000);

                        this.NavigationService.Navigate(new QuestionPage());
                    }
                }
                else
                {
                    wrongAnswers++;
                    Gradinita.WrongAnswerSound.Play();
                }
            };
            img3.Height = 150;
            img3.Width  = 150;
        }
 private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
 {
     DragDrop.DoDragDrop(this, this.DataContext, DragDropEffects.Copy);
 }
Beispiel #11
0
 private void AssociatedObject_PreviewMouseDown(object sender, MouseButtonEventArgs e)
 {
     _lastPoint = e.GetPosition(AssociatedObject);
     DragDrop.DoDragDrop(AssociatedObject, new object(), DragDropEffects.Move);
 }
Beispiel #12
0
 public override void StartDrag(AvaloniaObject dragSource, SharpTreeNode[] nodes)
 {
     DragDrop.DoDragDrop(Copy(nodes), DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
 }
Beispiel #13
0
        static void AttachDragAndDropFunctionality(StackPanel panel, Action <int, int> onOperationCompleted)
        {
            var       isDown          = false;
            var       isDragging      = false;
            var       startPoint      = new Point(0, 0);
            UIElement realDragSource  = null;
            var       dummyDragSource = new UIElement();

            void previewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                if (Equals(e.Source, panel))
                {
                }
                else
                {
                    isDown     = true;
                    startPoint = e.GetPosition(panel);
                }
            }

            void previewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                isDown     = false;
                isDragging = false;
                realDragSource?.ReleaseMouseCapture();
            }

            void previewMouseMove(object sender, MouseEventArgs e)
            {
                if (isDown)
                {
                    if (isDragging == false && (Math.Abs(e.GetPosition(panel).X - startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                                                Math.Abs(e.GetPosition(panel).Y - startPoint.Y) > SystemParameters.MinimumVerticalDragDistance))
                    {
                        isDragging     = true;
                        realDragSource = (UIElement)e.Source;
                        realDragSource.CaptureMouse();
                        DragDrop.DoDragDrop(dummyDragSource, new DataObject("UIElement", e.Source, true), DragDropEffects.Move);
                    }
                }
            }

            void dragEnter(object sender, DragEventArgs e)
            {
                if (e.Data.GetDataPresent("UIElement"))
                {
                    e.Effects = DragDropEffects.Move;
                }
            }

            void drop(object sender, DragEventArgs e)
            {
                if (e.Data.GetDataPresent("UIElement"))
                {
                    var dropTarget = e.Source as UIElement;
                    int dropTargetIndex = -1, i = 0;
                    foreach (UIElement element in panel.Children)
                    {
                        if (element.Equals(dropTarget))
                        {
                            dropTargetIndex = i;
                            break;
                        }

                        i++;
                    }

                    if (dropTargetIndex != -1)
                    {
                        var sourceIndex = panel.Children.IndexOf(realDragSource);

                        panel.Children.Remove(realDragSource);
                        panel.Children.Insert(dropTargetIndex, realDragSource);

                        onOperationCompleted?.Invoke(sourceIndex, dropTargetIndex);
                    }

                    isDown     = false;
                    isDragging = false;
                    realDragSource.ReleaseMouseCapture();
                }
            }

            panel.PreviewMouseLeftButtonDown += previewMouseLeftButtonDown;
            panel.PreviewMouseLeftButtonUp   += previewMouseLeftButtonUp;
            panel.PreviewMouseMove           += previewMouseMove;
            panel.DragEnter += dragEnter;
            panel.Drop      += drop;
            panel.AllowDrop  = true;
        }
Beispiel #14
0
        public void RefreshSamples(bool canGetDatas = true)
        {
            if (shouldUpdate == false)
            {
                return;
            }

            if (SysProcessManager == null)
            {
                return;
            }
            if (!mudoleHasInit)
            {
                return;
            }
            OnPropertyChanged("AllETLMount");

            var tasks = SysProcessManager.CurrentProcessTasks.Where(d => d.Publisher == this).ToList();

            if (tasks.Any())
            {
                var str = $"{Name}已经有任务在执行,由于调整参数,是否要取消当前任务重新执行?\n 【取消】:【不再提醒】";
                if (isErrorRemind == false)
                {
                    XLogSys.Print.Warn($"{Name}已经有任务在执行,请在任务管理器中取消该任务后再刷新");
                    return;
                }
                if (!MainDescription.IsUIForm)
                {
                    return;
                }
                var result =
                    MessageBox.Show(str, "提示信息", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Yes)
                {
                    foreach (var item in tasks)
                    {
                        item.Remove();
                    }
                    XLogSys.Print.Warn(str + "  已经取消");
                }
                else if (result == MessageBoxResult.Cancel)
                {
                    isErrorRemind = false;
                }
                else
                {
                    return;
                }
            }
            if (dataView == null && MainDescription.IsUIForm && IsUISupport)
            {
                var dock    = MainFrm as IDockableManager ?? ControlExtended.DockableManager;
                var control = dock?.ViewDictionary.FirstOrDefault(d => d.Model == this);
                if (control != null)
                {
                    if (control.View is IRemoteInvoke)
                    {
                        var invoke = control.View as IRemoteInvoke;
                        invoke.RemoteFunc = DropAction;
                    }
                    dynamic dy = control.View;

                    dataView     = dy.DataList;
                    scrollViewer = dy.ScrollViewer;

                    alltoolList     = dy.ETLToolList;
                    currentToolList = dy.CurrentETLToolList;
                    currentToolList.MouseDoubleClick += (s, e) =>
                    {
                        if (e.ChangedButton != MouseButton.Left)
                        {
                            return;
                        }
                        var process = currentToolList.SelectedItem as IColumnProcess;
                        if (process == null)
                        {
                            return;
                        }
                        var oldProp = process.UnsafeDictSerializePlus();
                        var window  = PropertyGridFactory.GetPropertyWindow(process);
                        window.Closed += (s2, e2) =>
                        {
                            if (
                                (oldProp.IsEqual(process.UnsafeDictSerializePlus()) == false && IsAutoRefresh).SafeCheck
                                    ("检查模块参数是否修改", LogType.Debug))
                            {
                                RefreshSamples();
                            }
                        };
                        window.ShowDialog();
                    };
                    dragMgr = new ListViewDragDropManager <IColumnProcess>(currentToolList);
                    dragMgr.ShowDragAdorner = true;

                    alltoolList.MouseMove += (s, e) =>
                    {
                        if (e.LeftButton == MouseButtonState.Pressed)
                        {
                            var attr = alltoolList.SelectedItem as XFrmWorkAttribute;
                            if (attr == null)
                            {
                                return;
                            }

                            var data = new DataObject(typeof(XFrmWorkAttribute), attr);
                            try
                            {
                                DragDrop.DoDragDrop(control.View as UserControl, data, DragDropEffects.Move);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    };
                }
            }
            if (dataView == null)
            {
                return;
            }
            Analyzer.Items.Clear();

            var alltools = CurrentETLTools.Take(ETLMount).ToList();
            var func     = alltools.Aggregate(isexecute: false, analyzer: Analyzer);

            if (!canGetDatas)
            {
                return;
            }
            SmartGroupCollection.Clear();
            Documents.Clear();
            shouldUpdate = false;
            var i = 0;

            foreach (var currentEtlTool in CurrentETLTools)
            {
                (currentEtlTool).ETLIndex = i++;
            }
            shouldUpdate = true;
            if (!MainDescription.IsUIForm)
            {
                return;
            }
            all_columns.Clear();
            dataView.Columns.Clear();

            AddColumn("", alltools);
            var temptask = TemporaryTask.AddTempTask(Name + "_转换",
                                                     func(new List <IFreeDocument>()).Take(SampleMount),
                                                     data =>
            {
                ControlExtended.UIInvoke(() =>
                {
                    foreach (var key in data.GetKeys().Where(d => all_columns.Contains(d) == false).OrderBy(d => d))
                    {
                        AddColumn(key, alltools);
                        DeleteColumn("");
                        all_columns.Add(key);
                    }

                    Documents.Add((data));
                    InitUI();
                });
            }, r =>
            {
                var tool      = CurrentTool;
                var outputCol = new List <string>();
                var inputCol  = new List <string>();

                if (tool != null)
                {
                    inputCol.Add(tool.Column);

                    var transformer = tool as IColumnDataTransformer;
                    if (transformer != null)
                    {
                        if (transformer is CrawlerTF)
                        {
                            var crawler = transformer as CrawlerTF;
                            outputCol   = crawler?.Crawler?.CrawlItems.Select(d => d.Name).ToList();
                        }
                        else if (transformer is ETLBase)
                        {
                            var etl    = transformer as ETLBase;
                            var target = etl.GetModule <SmartETLTool>(etl.ETLSelector.SelectItem);
                            outputCol  = target?.Documents.GetKeys().ToList();
                            inputCol.AddRange(etl.MappingSet.Split(' ').Select(d => d.Split(':')[0]));
                        }
                        else
                        {
                            outputCol = transformer.NewColumn.Split(' ').ToList();
                        }
                        SmartGroupCollection.Where(d => outputCol != null && outputCol.Contains(d.Name))
                        .Execute(d => d.GroupType = GroupType.Output);
                        SmartGroupCollection.Where(d => inputCol.Contains(d.Name))
                        .Execute(d => d.GroupType = GroupType.Input);
                    }
                }

                var firstOutCol = outputCol?.FirstOrDefault();
                if (firstOutCol != null)
                {
                    var index = all_columns.IndexOf(firstOutCol);
                    if (index != -1 && ETLMount < AllETLMount)
                    {
                        scrollViewer.ScrollToHorizontalOffset(index * CellWidth);
                    }
                }
                var nullgroup = SmartGroupCollection.FirstOrDefault(d => string.IsNullOrEmpty(d.Name));
                nullgroup?.Value.AddRange(
                    alltools.Where(
                        d =>
                        Documents.GetKeys().Contains(d.Column) == false &&
                        string.IsNullOrEmpty(d.Column) == false));
                nullgroup?.OnPropertyChanged("Value");
            }
                                                     , SampleMount);

            temptask.Publisher  = this;
            temptask.IsSelected = true;
            SysProcessManager.CurrentProcessTasks.Add(temptask);
        }
Beispiel #15
0
        private void treeView_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.m_bEditMode)
            {
                m_CurrentEditTextBox.Focus();
            }
            m_vCurrentMousePos = System.Windows.Forms.Cursor.Position;
            try
            {
                if (m_Test2.IsVisible)
                {
                    //Point l_vItemPos = m_Test2.PointToScreen(new Point(0d, 0d));
                    //m_Test2.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
                    //Size l_Size = m_Test2.DesiredSize;
                    //l_Size.Width += l_vItemPos.X;
                    //l_Size.Height += l_vItemPos.Y;
                    //m_Test.Header = l_vItemPos.ToString() + ",RB:" + l_Size.ToString() + "," + m_vCurrentMousePos.ToString();
                }
            }
            catch (Exception exp)
            {
                exp.ToString();
            }
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    System.Drawing.Point l_vCurrentPosition = System.Windows.Forms.Cursor.Position;
                    if ((Math.Abs(l_vCurrentPosition.X - m_vLastMouseDown.X) > m_dbTreeViewItemMinHeight) || (Math.Abs(l_vCurrentPosition.Y - m_vLastMouseDown.Y) > m_dbTreeViewItemMinHeight))
                    {
                        m_DraggedTreeViewItem = (TreeViewItem)m_Treeview.SelectedItem;
                        if (m_DraggedTreeViewItem != null)
                        {
                            DragDropEffects finalDropEffect = DragDrop.DoDragDrop(m_Treeview, m_Treeview.SelectedValue, DragDropEffects.Move);
                            //Checking target is not null and item is dragging(moving)
                            if (finalDropEffect == DragDropEffects.Move)
                            {
                                if ((m_TargetTreeViewItem != null))
                                {
                                    // A Move drop was accepted
                                    if (m_DraggedTreeViewItem != m_TargetTreeViewItem)
                                    {
                                        int l_iIsAddToChild = IsAddToNode(m_TargetTreeViewItem, m_vCurrentMousePos);
                                        if (m_DraggedTreeViewItem.Parent != null)
                                        {
                                            System.Diagnostics.Debug.WriteLine("remove child");
                                            CommonFunction.RemoveChild(m_DraggedTreeViewItem.Parent, m_DraggedTreeViewItem);
                                        }
                                        TreeViewItem l_TargetParent = m_TargetTreeViewItem.Parent as TreeViewItem;
                                        string       l_strrr        = m_TargetTreeViewItem.GetType().ToString();
                                        if (l_TargetParent == null)
                                        {
                                            TreeView l_TreeView = m_TargetTreeViewItem.Parent as TreeView;
                                            if (l_TreeView != null)
                                            {
                                                int l_iIndex = l_TreeView.Items.IndexOf(m_TargetTreeViewItem);
                                                //if (l_TreeView.Items.Count > l_iIndex + 1)
                                                {
                                                    System.Diagnostics.Debug.WriteLine("add child-1");
                                                    TreeViewItem l_TreeViewItem = CopyItem(m_DraggedTreeViewItem);
                                                    //l_TreeView.Items.Insert(l_iIndex + 1, m_DraggedTreeViewItem);
                                                    l_TreeView.Items.Insert(l_iIndex + 1, l_TreeViewItem);
                                                }
                                                //else
                                                //{
                                                //    System.Diagnostics.Debug.WriteLine("add child0");
                                                //    m_TargetTreeViewItem.Items.Add(m_DraggedTreeViewItem);
                                                //}
                                            }
                                            else
                                            {
                                                System.Diagnostics.Debug.WriteLine("add child1");
                                                TreeViewItem l_TreeViewItem = CopyItem(m_DraggedTreeViewItem);
                                                m_TargetTreeViewItem.Items.Add(l_TreeViewItem);
                                                //m_TargetTreeViewItem.Items.Add(m_DraggedTreeViewItem);
                                            }
                                        }
                                        else
                                        {
                                            int l_iIndex = l_TargetParent.Items.IndexOf(m_TargetTreeViewItem);
                                            switch (l_iIsAddToChild)
                                            {
                                            case -1:
                                                System.Diagnostics.Debug.WriteLine("add child2");
                                                l_TargetParent.Items.Insert(l_iIndex, m_DraggedTreeViewItem);
                                                break;

                                            case 0:
                                                System.Diagnostics.Debug.WriteLine("add child3");
                                                m_TargetTreeViewItem.Items.Add(m_DraggedTreeViewItem);
                                                break;

                                            case 1:
                                                System.Diagnostics.Debug.WriteLine("add child4");
                                                if (l_iIndex + 1 < l_TargetParent.Items.Count)
                                                {
                                                    l_TargetParent.Items.Insert(l_iIndex + 1, m_DraggedTreeViewItem);
                                                }
                                                else
                                                {
                                                    l_TargetParent.Items.Add(m_DraggedTreeViewItem);
                                                }
                                                break;
                                            }
                                        }
                                        if (f_TreeViewItemMoved != null)
                                        {
                                            f_TreeViewItemMoved(m_DraggedTreeViewItem, m_TargetTreeViewItem);
                                        }
                                        m_DraggedTreeViewItem.IsSelected = true;
                                        m_DraggedTreeViewItem.BringIntoView();
                                        m_DraggedTreeViewItem.Focus();
                                        m_TargetTreeViewItem  = null;
                                        m_DraggedTreeViewItem = null;
                                    }
                                }
                                else
                                {
                                    TreeViewItem l_DraggedItem = (TreeViewItem)m_DraggedTreeViewItem;
                                    if (l_DraggedItem.Parent != null)
                                    {
                                        CommonFunction.RemoveChild(l_DraggedItem.Parent, l_DraggedItem);
                                    }
                                    this.m_Treeview.Items.Add(l_DraggedItem);
                                    m_DraggedTreeViewItem.IsSelected = true;
                                    m_DraggedTreeViewItem.BringIntoView();
                                    m_DraggedTreeViewItem.Focus();
                                    if (f_TreeViewItemMoved != null)
                                    {
                                        f_TreeViewItemMoved(l_DraggedItem, null);
                                    }
                                    m_TargetTreeViewItem  = null;
                                    m_DraggedTreeViewItem = null;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception l_Exp)
            {
                String l_str = l_Exp.ToString();
            }
        }
Beispiel #16
0
        private void WireDragAndDrop()
        {
            var playlistDropEvent = this.PlaylistListBox.ItemContainerStyle.RegisterEventSetter <DragEventArgs>(DropEvent, x => new DragEventHandler(x))
                                    .Merge(this.PlaylistListBox.Events().Drop.Select(x => Tuple.Create((object)null, x)));

            // Local, YouTube and SoundCloud songs
            playlistDropEvent
            .Where(x => x.Item2.Data.GetDataPresent(DataFormats.StringFormat) && (string)x.Item2.Data.GetData(DataFormats.StringFormat) == DragDropHelper.SongSourceFormat)
            .Subscribe(x =>
            {
                int?targetIndex = x.Item1 == null ? (int?)null : ((PlaylistEntryViewModel)((ListBoxItem)(x.Item1)).DataContext).Index;

                var addCommand = this.shellViewModel.CurrentSongSource.AddToPlaylistCommand;
                if (addCommand.CanExecute(null))
                {
                    addCommand.Execute(targetIndex);
                }

                x.Item2.Handled = true;
            });

            // YouTube links (e.g from the browser)
            playlistDropEvent
            .Where(x => x.Item2.Data.GetDataPresent(DataFormats.StringFormat))
            .Where(x =>
            {
                var url = (string)x.Item2.Data.GetData(DataFormats.StringFormat);
                Uri uriResult;
                bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

                string urlDontCare;

                return(result && DownloadUrlResolver.TryNormalizeYoutubeUrl(url, out urlDontCare));
            })
            .SelectMany(async x =>
            {
                var url         = (string)x.Item2.Data.GetData(DataFormats.StringFormat);
                int?targetIndex = x.Item1 == null ? (int?)null : ((PlaylistEntryViewModel)((ListBoxItem)(x.Item1)).DataContext).Index;

                if (this.shellViewModel.DirectYoutubeViewModel.AddToPlaylistCommand.CanExecute(null))
                {
                    await this.shellViewModel.DirectYoutubeViewModel.AddDirectYoutubeUrlToPlaylist(new Uri(url), targetIndex);
                }

                x.Item2.Handled = true;

                return(Unit.Default);
            }).Subscribe();

            // Moving items inside the playlist
            const string movePlaylistSongFormat = "MovePlaylistSong";

            this.PlaylistListBox.ItemContainerStyle.RegisterEventSetter <MouseEventArgs>(MouseMoveEvent, x => new MouseEventHandler(x))
            .Where(x => x.Item2.LeftButton == MouseButtonState.Pressed && this.shellViewModel.CurrentPlaylist.SelectedEntries.Any())
            .Subscribe(x => DragDrop.DoDragDrop((ListBoxItem)x.Item1, movePlaylistSongFormat, DragDropEffects.Move));

            playlistDropEvent
            .Where(x => x.Item2.Data.GetDataPresent(DataFormats.StringFormat) && (string)x.Item2.Data.GetData(DataFormats.StringFormat) == movePlaylistSongFormat)
            .Subscribe(x =>
            {
                if (this.shellViewModel.CurrentPlaylist.MovePlaylistSongCommand.CanExecute(null))
                {
                    int?targetIndex = x.Item1 == null ? (int?)null : ((PlaylistEntryViewModel)((ListBoxItem)(x.Item1)).DataContext).Index;

                    this.shellViewModel.CurrentPlaylist.MovePlaylistSongCommand.Execute(targetIndex);
                }

                x.Item2.Handled = true;
            });
        }
 private void TextBox_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
 {
     DragDrop.DoDragDrop(TextBox, "Foo", DragDropEffects.Move);
     e.Handled = true;
 }
Beispiel #18
0
        private void StartDrag(MouseEventArgs mouseEventArgs, TreeView treeView, TreeViewItem item)
        {
            // Can only drop actual favorites (or favorite groups)...
            DataObject data = null;

            var selectedItem = treeView.SelectedItem as HierarchicalViewModelBase;

            if (selectedItem is FavoriteViewModel <T> )
            {
                var    selected = treeView.SelectedItem as FavoriteViewModel <T>;
                string desc     = "";
                data = new DataObject(typeof(T).Name, selected);

                if (selected.IsGroup)
                {
                    desc = String.Format("Favorite Folder: Name={0} [FavoriteID={1}]", selected.GroupName, selected.FavoriteID);
                }
                else
                {
                    desc = String.Format("{0} : Name={1} [ID1={2}, ID2={3}, FavoriteID={4}]", typeof(T).Name, selected.DisplayLabel, selected.Model.ID1, selected.Model.ID2, selected.FavoriteID);
                    data.SetData(PinnableObject.DRAG_FORMAT_NAME, Provider.CreatePinnableObject(selected));
                }

                data.SetData(DataFormats.Text, desc);
            }
            else if (selectedItem is V)
            {
                data = new DataObject(PinnableObject.DRAG_FORMAT_NAME, Provider.CreatePinnableObject(treeView.SelectedItem as V));
            }

            if (data != null)
            {
                _dropScope           = treeView;
                _dropScope.AllowDrop = true;

                GiveFeedbackEventHandler feedbackhandler = new GiveFeedbackEventHandler(DropScope_GiveFeedback);
                item.GiveFeedback += feedbackhandler;

                var handler = new DragEventHandler((s, e) => {
                    TreeViewItem destItem = GetHoveredTreeViewItem(e);
                    e.Effects             = DragDropEffects.None;
                    if (destItem != null)
                    {
                        destItem.IsSelected = true;
                        var destModel       = destItem.Header as FavoriteViewModel <T>;
                        if (destModel != selectedItem && !selectedItem.IsAncestorOf(destModel))
                        {
                            if (destModel != null)
                            {
                                if (destModel.IsGroup)
                                {
                                    e.Effects = DragDropEffects.Move;
                                }
                            }
                            else
                            {
                                if (destItem.Header is ViewModelPlaceholder)
                                {
                                    e.Effects = DragDropEffects.Move;
                                }
                            }
                        }
                    }
                    e.Handled = true;
                });

                treeView.PreviewDragEnter += handler;
                treeView.PreviewDragOver  += handler;

                var dropHandler = new DragEventHandler(treeView_Drop);
                treeView.Drop += dropHandler;


                try {
                    _IsDragging = true;
                    DragDrop.DoDragDrop(item, data, DragDropEffects.Copy | DragDropEffects.Move | DragDropEffects.Link);
                } finally {
                    _IsDragging = false;
                    treeView.PreviewDragEnter -= handler;
                    treeView.PreviewDragOver  -= handler;
                    treeView.Drop             -= dropHandler;
                }
            }

            InvalidateVisual();
        }
Beispiel #19
0
        private void lbl1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label lbl = (Label)sender;

            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
        }
Beispiel #20
0
 private void ImgMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     Image_To_Drag = (Image)e.Source;
     DragDrop.DoDragDrop(Image_To_Drag, Image_To_Drag, DragDropEffects.Move);
 }
Beispiel #21
0
 public override void DoDragDropCopy(object dragDropData)
 {
     DragDrop.DoDragDrop(_control, dragDropData, DragDropEffects.Copy);
 }
Beispiel #22
0
        private void source_MouseDown(object sender, MouseButtonEventArgs e)
        {
            DataObject data = new DataObject(typeof(Image), (Image)sender);

            DragDrop.DoDragDrop((Image)sender, data, DragDropEffects.Copy);
        }
 private void Border_OnMouseDown(object sender, MouseButtonEventArgs e)
 {
     Debug.WriteLine("Border_OnMouseDown!");
     DragDrop.DoDragDrop((DependencyObject)sender, "", DragDropEffects.All);
 }
Beispiel #24
0
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                this.dragStartPoint = null;
            }

            if (this.dragStartPoint.HasValue)
            {
                // XamlWriter.Save() has limitations in exactly what is serialized,
                // see SDK documentation; short term solution only;
                string     xamlString = XamlWriter.Save(this.Content);
                DragObject dataObject = new DragObject();
                dataObject.Xaml  = xamlString;
                dataObject.Class = dataObject.GetClassByTag();
                this.Tag         = dataObject.Class;


                WrapPanel panel = VisualTreeHelper.GetParent(this) as WrapPanel;
                if (panel != null)
                {
                    // desired size for DesignerCanvas is the stretched Toolbox item size
                    double scale = 1.3;
                    dataObject.DesiredSize = new Size(panel.ItemWidth * scale, panel.ItemHeight * scale);
                }

                if (DesignerItem != null)
                {
                    dataObject.DesignerItem = DesignerItem;
                }

                #region  аннее
                //var _dataObject = new object();
                //object designerItem = this;
                //if (designerItem is DesignerItem)
                //{
                //    _dataObject = designerItem;
                //}
                //else
                //{
                //    // XamlWriter.Save() has limitations in exactly what is serialized,
                //    // see SDK documentation; short term solution only;
                //    string xamlString = XamlWriter.Save(this.Content);
                //    DragObject dataObject = new DragObject();
                //    dataObject.Xaml = xamlString;
                //    dataObject.Class = dataObject.GetClassByTag();
                //    this.Tag = dataObject.Class; WrapPanel panel = VisualTreeHelper.GetParent(this) as WrapPanel;

                //    if (panel != null)
                //    {
                //        // desired size for DesignerCanvas is the stretched Toolbox item size
                //        double scale = 1.3;
                //        dataObject.DesiredSize = new Size(panel.ItemWidth * scale, panel.ItemHeight * scale);
                //    }
                //    _dataObject = dataObject;
                //}
                #endregion

                DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy);

                e.Handled = true;
            }
        }
Beispiel #25
0
        public void RefreshSamples(bool canGetDatas = true)
        {
            if (SysProcessManager == null)
            {
                return;
            }
            if (SysProcessManager.CurrentProcessTasks.Any(d => d.Publisher == this))
            {
                XLogSys.Print.WarnFormat("{0}已经有任务在执行,请在执行完毕后再刷新,或取消该任务", this.Name);
                return;
            }
            if (dataView == null && MainDescription.IsUIForm && IsUISupport)
            {
                var dock    = MainFrm as IDockableManager ?? ControlExtended.DockableManager;
                var control = dock?.ViewDictionary.FirstOrDefault(d => d.Model == this);
                if (control != null)
                {
                    if (control.View is IRemoteInvoke)
                    {
                        var invoke = control.View as IRemoteInvoke;
                        invoke.RemoteFunc = DropAction;
                    }
                    dynamic dy = control.View;

                    dataView               = dy.DataList;
                    alltoolList            = dy.ETLToolList;
                    alltoolList.MouseMove += (s, e) =>
                    {
                        if (e.LeftButton == MouseButtonState.Pressed)
                        {
                            var attr = alltoolList.SelectedItem as XFrmWorkAttribute;
                            if (attr == null)
                            {
                                return;
                            }

                            var data = new DataObject(typeof(XFrmWorkAttribute), attr);
                            try
                            {
                                DragDrop.DoDragDrop(control.View as UserControl, data, DragDropEffects.Move);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    };
                }
            }
            Documents.Clear();

            var alltools = CurrentETLTools.Take(ETLMount).ToList();
            var hasInit  = false;
            var func     = Aggregate(d => d, alltools, false);

            if (!canGetDatas)
            {
                return;
            }
            var temptask = TemporaryTask.AddTempTask(this.Name + "_转换",
                                                     func(new List <IFreeDocument>()).Take(SampleMount),
                                                     data =>
            {
                ControlExtended.UIInvoke(() =>
                {
                    Documents.Add((data));
                    if (hasInit == false && Documents.Count > 2)
                    {
                        InitUI();
                        hasInit = true;
                    }
                });
            }, d =>
            {
                if (!hasInit)
                {
                    InitUI();
                    hasInit = true;
                }
            }
                                                     , SampleMount);

            temptask.Publisher = this;
            SysProcessManager.CurrentProcessTasks.Add(temptask);
        }
Beispiel #26
0
        void dg_dragsource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var data = new DataObject(typeof(object), new object());

            DragDrop.DoDragDrop(dg_dragsource, data, DragDropEffects.Link);
        }
Beispiel #27
0
    internal MainWin()
    {
        sel = new Selection(this);

        TestCase();

        Title      = "Restructor";
        FontFamily = new FontFamily("Consolas");

        dp = new DockPanel();

        var tbs = new ToolBarTray();

        tbs.Background = new SolidColorBrush(Color.FromRgb(0xA4, 0xB3, 0xC8));
        dp.Children.Add(tbs);
        DockPanel.SetDock(tbs, Dock.Top);

        var tb  = GUI.ToolBar(tbs);
        var res = GUI.TextBox(null, "Ready.");

        GUI.Button(this, tb, "New", ApplicationCommands.New, false,
                   () => { prog.New(); TreeChanged(); });
        GUI.Button(this, tb, "Open", ApplicationCommands.Open, false,
                   () => MessageBox.Show("Not Implimented: Open"));
        GUI.Button(this, tb, "Save", ApplicationCommands.Save, false, () =>
        {
            var cr = new CodeRenderText();
            prog.RenderCode(cr);
            var sw = new StreamWriter("text.restruct");
            sw.Write(cr.program);
            sw.Close();
            res.Text = "Saved Restructor Code.";
        });
        GUI.Button(this, tb, "Save As", ApplicationCommands.SaveAs, false,
                   () => MessageBox.Show("Not Implimented: SaveAs"));
        tb.Items.Add(GUI.TBSep());
        GUI.Button(this, tb, "Copy", ApplicationCommands.Copy, true,
                   () => Clipboard.SetText(sel.selected.ToString()));
        GUI.Button(this, tb, "Paste", ApplicationCommands.Paste, true,
                   () => { if (sel.selected is Node)
                           {
                               Replace(sel.selected as Node, Clipboard.GetText());
                           }
                   });
        GUI.Button(this, tb, "Undo", ApplicationCommands.Undo, false,
                   () => MessageBox.Show("Not Implimented: Undo"));
        tb.Items.Add(GUI.TBSep());
        GUI.Button(this, tb, "Restruct", new RsCommand(() =>
        {
            res.Text = prog.Restructor();
            TreeChanged();
        }));
        GUI.Button(this, tb, "Run", new RsCommand(
                       () => { res.Text = prog.GenCode(true, false); GC.Collect(); }));
        GUI.Button(this, tb, "Save Exe", new RsCommand(
                       () => { res.Text = prog.GenCode(false, false); GC.Collect(); }));
        GUI.Button(this, tb, "DBG", new RsCommand(
                       () => { res.Text = prog.GenCode(true, true); GC.Collect(); }));
        GUI.Button(this, tb, "DBGS", new RsCommand(
                       () => { res.Text = prog.GenCode(false, true); GC.Collect(); }));

        var tb2 = GUI.ToolBar(tbs);

        FocusManager.SetIsFocusScope(tb2, false);
        var tbsp = GUI.StackPanel(true);

        GUI.TextBox(tbsp, "<input>", s => Runtime.__commandlineargs = s.Split(' '));
        tbsp.Children.Add(res);
        tb2.Items.Add(tbsp);

        foreach (DependencyObject a in tb.Items)
        {
            ToolBar.SetOverflowMode(a, OverflowMode.Never);
        }
        foreach (DependencyObject a in tb2.Items)
        {
            ToolBar.SetOverflowMode(a, OverflowMode.Never);
        }

        TreeChanged();
        Content = dp;

        MouseWheel += (s, e) =>
        {
            scale *= 1.0 + e.Delta / 600.0;
            if (scale > 2)
            {
                scale = 2;
            }
            if (scale < 1)
            {
                scale = 1;
            }
            SetScale();
        };

        MouseLeftButtonDown += (s, e) =>
        {
            if (e.ClickCount > 1)
            {
                sel.SetEditMode();
            }
            else
            {
                sel.Selected();
            }
        };

        PreviewMouseLeftButtonDown += (s, e) =>
        {
            sel.ReSelectEditBox();
            dragstartpoint = Mouse.GetPosition(this);
        };

        MouseMove += (s, e) =>
        {
            sel.HoverMove(e.GetPosition(this));

            if (e.LeftButton == MouseButtonState.Pressed && dragnode == null)
            {
                Vector diff = dragstartpoint - Mouse.GetPosition(this);

                if ((Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                     Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance) &&
                    sel.selected != null)
                {
                    var seln = sel.selected as Node;
                    if (seln != null && !(seln.t is Unparsed))
                    {
                        dragnode = seln;
                        DataObject data =
                            new DataObject(DataFormats.UnicodeText, sel.selected.ToString());
                        DragDrop.DoDragDrop(sel.selectedui, data, DragDropEffects.Copy);
                        dragnode = null;
                    }
                }
            }
        };

        DragOver += (s, e) =>
        {
            sel.HoverMove(e.GetPosition(this));
            if (sel.hover == dragnode)
            {
                e.Effects = DragDropEffects.None;
            }
        };

        Drop += (s, e) =>
        {
            if (e.Data.GetDataPresent(DataFormats.UnicodeText))
            {
                if (sel.hover != null && sel.hover is Node)
                {
                    Replace(sel.hover as Node, e.Data.GetData(DataFormats.UnicodeText) as string);
                }
            }
        };

        KeyDown += (s, e) =>
        {
            switch (e.Key)
            {
            default:
                sel.HandleKey(e.Key);
                break;
            }
        };

        TextInput += (s, e) =>
                     sel.SetEditMode(e.Text);
    }
Beispiel #28
0
 public void DoDragDrop(object sender, object data)
 {
     DragDrop.DoDragDrop(sender.As <FrameworkElement>(), new DataObject(TypeOfSource, data), DragDropEffects.Move);
 }
        /// <summary>
        /// This handler monitors the mouse movement and initiates the drag/drop operation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnMouseMove(object sender, MouseEventArgs e)
        {
            IList collection = (IList)AssociatedObject.ItemsSource ?? AssociatedObject.Items;

            // If the mouse is moving with the mouse button down, then initiate the drag operation.
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                // Find the row and only drag it if it is already selected.
                UIElement   source = e.OriginalSource as UIElement;
                DataGridRow row    = (source != null) ? source.GetParent <DataGridRow>() : null;
                if ((row != null) && row.IsSelected)
                {
                    // Perform the drag operation
                    DragDropEffects finalDropEffect = DragDrop.DoDragDrop(row, row.Item, DragDropEffects.Move);
                    if ((finalDropEffect == DragDropEffects.Move) && (_target != null))
                    {
                        // A Move drop was accepted
                        // Determine the index of the item being dragged and the drop
                        // location. If they are difference, then move the selected
                        // item to the new location.
                        int oldIndex = collection.IndexOf(row.Item);
                        int newIndex = collection.IndexOf(_target);
                        if (newIndex == -1 && _target == CollectionView.NewItemPlaceholder)
                        {
                            newIndex = collection.Count - 1;
                        }

                        if (oldIndex != newIndex && oldIndex >= 0 && newIndex >= 0)
                        {
                            var dropStarted = DropStarted;
                            if (dropStarted != null)
                            {
                                dropStarted.Invoke(this, new DataGridRowDropEventArgs(row.Item, oldIndex, newIndex));
                            }

                            Type type = collection.GetType();
                            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObservableCollection <>))
                            {
#if !WPF_TOOLKIT
                                dynamic dCollection = collection;
                                dCollection.Move(oldIndex, newIndex);
#else
                                var methodInfo = type.GetMethod("Move");
                                methodInfo.Invoke(collection, new object[] { oldIndex, newIndex });
#endif
                            }
                            else
                            {
                                collection.RemoveAt(oldIndex);
                                collection.Insert(newIndex, row.Item);
                            }

                            var dropFinished = DropFinished;
                            if (dropFinished != null)
                            {
                                dropFinished.Invoke(this, new DataGridRowDropEventArgs(row.Item, oldIndex, newIndex));
                            }
                        }
                        _target = null;
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Handles the mouse move routed event.
        /// </summary>
        /// <param name="sender">The object where the event handler is attached.</param>
        /// <param name="mouseButtonEventArgs">The event data.</param>
        private static void OnDragSourcePreviewMouseMove(object sender, MouseEventArgs mouseEventArgs)
        {
            // Extract the strongly typed values from the generic arguments.
            UIElement uiElement = sender as UIElement;

            // This attempts to decode the mouse gestures into an invocation of the drag and drop operation.  To begin, the
            // drag-and-drop operation is only initiated when the left mouse button is pressed and dragged a distance large enough
            // to insure a deliberate action on the part of the user.  Furthermore, hitting an input element, such as the expander
            // buttons on TreeView controls, can cause a recursive call to this method.  Normally, the 'DoDragDrop' method would
            // capture all mouse activity, but that is not the case when the mouse generates an input command.
            if (mouseEventArgs.LeftButton == MouseButtonState.Pressed && !DragDropHelper.isDragging)
            {
                // The drag and drop operation is invoked only when an object has been selected.
                if (DragDropHelper.sourceData != null)
                {
                    // Mouse movements are ignored if the mouse hasn't moved far enough from starting point.  This prevents
                    // accidental drag-and-drop operations by insuring that the user has made a conscious effort to move the mouse
                    // with the left mouse button down.
                    Point currentPosition = mouseEventArgs.GetPosition(uiElement);
                    Point startPosition   = DragDropHelper.initialPosition;
                    if (Math.Abs(currentPosition.X - startPosition.X) >= SystemParameters.MinimumHorizontalDragDistance ||
                        Math.Abs(currentPosition.Y - startPosition.Y) >= SystemParameters.MinimumVerticalDragDistance)
                    {
                        // The top level window is hooked into the drag and drop events so it can provide movement commands for the
                        // dragged adorner even when the adorner is not over the source or target elements.
                        Window  topWindow         = (Window)DragDropHelper.FindAncestor(typeof(Window), uiElement);
                        Boolean previousAllowDrop = topWindow.AllowDrop;

                        // This visual layer sits on top of all other visual layers and provides rendinging for the visual element
                        // used to display the dragged object like a cursor.  A cursor-like visual element is created in this layer
                        // to track the movement of the mouse and to give feedback about what kind of element is to be dropped.
                        AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(uiElement);

                        try
                        {
                            // This is the data item that will be dragged about.  Each of the drop targets can examine this object
                            // to see what operations are acceptable.
                            DataObject data = new DataObject(DragDropHelper.DataFormat.Name, DragDropHelper.sourceData);

                            // This creates a visual element that provides a picture of the object to be dragged.  It uses the
                            // adorner layer for rending and follows the cursor around the screen.  Note that the opacity of the
                            // adorner is fixed at a value that was reverse engineered from Microsoft Windows File Explorer.
                            DragDropHelper.draggedAdorner = new DraggedAdorner(
                                uiElement,
                                DragDropHelper.sourceData,
                                GetDragDropTemplate(uiElement));
                            adornerLayer.Add(DragDropHelper.draggedAdorner);

                            // Adding these events to the top window allows the dragged adorner to come up even when it is not over the
                            // source or target window.
                            topWindow.AllowDrop  = true;
                            topWindow.DragEnter += OnTopWindowDragEnter;
                            topWindow.DragOver  += OnTopWindowDragOver;

                            // This does all the hard work of dragging and dropping.  Note that the flag prevents recursive calls
                            // to the DoDragDrop when the source involves some visual element that can generate input commands
                            // through the mouse, such as expanding or collapsing a node in a TreeView.
                            DragDropHelper.isDragging = true;
                            DragDrop.DoDragDrop((DependencyObject)sender, data, DragDropEffects.Move);
                        }
                        finally
                        {
                            // This flag is designed to prevent recursive calls to the drag and drop operation.
                            DragDropHelper.isDragging = false;

                            // At this point the drag and drop operation is complete and the top window can be restored to its
                            // previous state.
                            topWindow.AllowDrop  = previousAllowDrop;
                            topWindow.DragEnter -= OnTopWindowDragEnter;
                            topWindow.DragOver  -= OnTopWindowDragOver;

                            // This disposes of the cursor-like object that displays the dragged object as the mouse moves.
                            adornerLayer.Remove(DragDropHelper.draggedAdorner);
                            DragDropHelper.draggedAdorner = null;
                        }

                        // This ends the operation started when the left mouse button was pressed.
                        DragDropHelper.sourceData = null;
                    }
                }
            }
            else
            {
                // This will cancel any drag-and-drop operation that was started but not completed.  Normally the end of the
                // operation or the left mouse button being released will clear the status, but in rare cases it's possible to move
                // the mouse off the object before the minimum distance is recognized and then leave the window.  This insures that
                // the drag-and-drop operation is in the initial state when that happens.
                if (DragDropHelper.sourceData != null)
                {
                    DragDropHelper.sourceData = null;
                }
            }
        }