对于WPF拖拽问题网上有很多,一般就是一个控件的移动,今天想做一个效果,效果是这样的:
页面分左右两部分,左边是canvas是空的,右边的canvas中有一个矩形,我要把矩形拖到到左侧,拖完后右侧的矩形不消失,也就是说在左边复制了一个矩形,以下是代码
public StackPanel() { InitializeComponent(); this.rectImage.PreviewMouseMove += new MouseEventHandler(rect_PreviewMouseMove); this.Canvas1 .DragOver +=new DragEventHandler(Canvas1_DragOver); this.Canvas1.Drop += new DragEventHandler(Canvas1_Drop); } void rect_PreviewMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { DataObject data = new DataObject(typeof(Rectangle), this.rectImage); DragDrop.DoDragDrop(this.rectImage, data, DragDropEffects.Move); } } void Canvas1_DragOver(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent(typeof(Rectangle))) { e.Effects = DragDropEffects.None; e.Handled = true; } } void Canvas1_Drop(object sender, DragEventArgs e) { IDataObject data =new DataObject (); data= e.Data; if (data.GetDataPresent(typeof(Rectangle))) { Rectangle rect = new Rectangle(); rect = data.GetData(typeof(Rectangle)) as Rectangle; this.Canvas2.Children.Remove(rect); this.Canvas1.Children.Add(rect); } }
上面的代码实现的是移动后右侧的矩形就消失了,但是我想不消失,但是把
this.Canvas2.Children.Remove(rect);这句代码注释了后就会报错,这里该怎么做呢,为什么会出现这个错呢?我刚接触WPF,不明白,高手帮忙
- 3 回答
- 0 关注
- 560 浏览
添加回答
举报
0/150
提交
取消