WPF中拖动控件,实现位置随意摆放[1]

来源:互联网 发布:柠檬网络电视 编辑:程序博客网 时间:2024/04/30 14:35
一般的拖动程序,都是实现 MouseLeftButtonDown,MouseLeftButtonUp,MouseMove 这三个事件,大多数的情况下,拖动过程中,都是在 MouseMove 这个函数里面设置控件的坐标。

以下的代码,只有一点点的不同,在拖动过程中,原控件还是在原来位置,只是新产生了一个按控件外形生成的阴影图片,然后设置该阴影图片的位置,最后,鼠标离开的时候,设置原控件的位置。。。

    private void ContainerPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)    {        if ((e.ClickCount <= 1) && (sender != e.Source))        {            ElementUI source = e.Source as ElementUI;            this.SelectedItem = source;            NodeUI eui = e.Source as NodeUI;            if ((eui != null) && eui.DataSource.CanDrag)            {                NodeUI nodeUI = (NodeUI) e.Source;                Point point = new Point(nodeUI.CenterX, nodeUI.CenterY);                this.startPoint = base.ToPlot(e.GetPosition(this));                this.offsetVector = (Vector) (this.startPoint - point);                this.CreateDragShade(nodeUI);                this.dragShade.CaptureMouse();//阴影捕获鼠标                e.Handled = true;            }        }    }    private void ContainerPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)    {        if (e.ClickCount <= 1)        {            NodeUI selectedItem = this.SelectedItem as NodeUI;            if ((selectedItem != null) && this.dragShade.IsMouseCaptured)            {                Point point = base.ToPlot(e.GetPosition(this));                double dx = point.X - this.startPoint.X;                double dy = point.Y - this.startPoint.Y;                Node dataSource = selectedItem.DataSource;                if ((dataSource != null) && dataSource.CanDrag)                {                    dataSource.PerformDrag(dx, dy);                }            }            this.dragShade.ReleaseMouseCapture();            this.dragShade.Visibility = Visibility.Hidden;            base.Children.Remove(this.dragShade);        }    }    private void ContainerPanel_MouseMove(object sender, MouseEventArgs e)    {        if ((e.LeftButton == MouseButtonState.Pressed) && this.dragShade.IsMouseCaptured)        {            Point point = base.ToPlot(e.GetPosition(this));            PlotPanel.SetCenterX(this.dragShade, point.X - this.offsetVector.X);            PlotPanel.SetCenterY(this.dragShade, point.Y - this.offsetVector.Y);        }    }    private void CreateDragShade(NodeUI nodeUI)    {        VisualBrush brush = new VisualBrush();        brush.Stretch = Stretch.Fill;        brush.Visual = nodeUI;        brush.Opacity = 0.6;        this.dragShade.Width = nodeUI.ActualWidth;        this.dragShade.Height = nodeUI.ActualHeight;        this.dragShade.Stroke = Brushes.Transparent;        this.dragShade.Fill = brush;        this.dragShade.Stretch = Stretch.Fill;        PlotPanel.SetCenterX(this.dragShade, nodeUI.CenterX);        PlotPanel.SetCenterY(this.dragShade, nodeUI.CenterY);        this.dragShade.Visibility = Visibility.Visible;        base.Children.Add(this.dragShade);    }


原创粉丝点击