如何将列表框项目拖到单独的SelectedItem附近

时间:2018-07-24 13:00:35

标签: c# .net wpf drag-and-drop

我要拖动列表框选择的项目。拖动功能运行良好。我的要求是,从列表框中的任何其他位置开始拖动时,不应发生拖动。我确实是这样,但这是行不通的。请有人建议我实现这一目标,

Database /dir1/activemq-db/lock is locked by another server. This broker is now in slave mode waiting a lock to be acquired | org.apache.activemq.store.SharedFileLocker | main

Please refer the screenshot

1 个答案:

答案 0 :(得分:0)

执行此操作,通过使用System.Windows.Media.VisualTreeHelper.HitTest(this, point),将当前元素显示在鼠标下方。我认为这会对您有所帮助。

private bool IsDrag { get; set; }              

        protected override void OnAttached()
        {            
            this.AssociatedObject.Drop += AssociatedObject_Drop;            
            this.AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObject_PreviewMouseLeftButtonDown;
            this.AssociatedObject.PreviewMouseMove += AssociatedObject_PreviewMouseMove;

        }

        private void AssociatedObject_PreviewMouseMove(object sender, MouseEventArgs e)
        {                                  
            if (e.LeftButton == MouseButtonState.Pressed)
            {               
                if(IsDrag)
                {
                    StartDrag(sender);
                }
            }
        }

        private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            IsDrag = false;    

            if(sender is ListBox)
            {
                Point initialPoint = e.GetPosition((UIElement)sender);
                var histPoint = VisualTreeHelper.HitTest(sender as ListBox, initialPoint);

                if (histPoint.VisualHit != null)
                {
                    if (histPoint.VisualHit is TextBlock || histPoint.VisualHit is Border)
                    {
                        IsDrag = true;
                    }
                }
            }            
        }                   

        private void StartDrag(object sender)
        {            
            if (sender is ListBox)
            {
                var listBox = (sender as ListBox);
                if (listBox != null)
                {
                    var selectedMember = listBox.SelectedItem;
                    if (selectedMember != null)
                    {
                        DragDrop.DoDragDrop(listBox, selectedMember, DragDropEffects.Copy);
                    }
                }
            }           
        }