在MainWindow中定义了MouseMove事件之后,自定义控件中的其它事件就变的无效了(附源码)求指点
可以运行,但运行后MainWindow中的所有控件都可拖动,但是像TextBlock拖动到其它控件上时,其数据无法传到其它控件上,如果把MainWindow中的拖动事件去掉,就可以,求高手指点一下,万分感谢,在线等待当中......
自定义控件源码:
public partial class Box : UserControl { public Box() { InitializeComponent(); } protected override void OnDragEnter(DragEventArgs e) { base.OnDragEnter(e); collections = MyBox.Children; if (e.Data.GetDataPresent(DataFormats.StringFormat)) { string data_string = (string)e.Data.GetData(DataFormats.StringFormat); TextBlock tb = new TextBlock(); tb.Text = data_string; MyBox.Children.Add(tb); } } protected override void OnGiveFeedback(GiveFeedbackEventArgs e) { base.OnGiveFeedback(e); } protected override void OnDrop(DragEventArgs e) { base.OnDrop(e); if (e.Data.GetDataPresent(DataFormats.StringFormat)) { string dataString = (string)e.Data.GetData(DataFormats.StringFormat); TextBlock tb = new TextBlock(); tb.Text = dataString; MyBox.Children.Add(tb); if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey)) { e.Effects = DragDropEffects.Copy; } else { e.Effects = DragDropEffects.Move; } } e.Handled = true; } protected override void OnDragOver(DragEventArgs e) { base.OnDragOver(e); if (e.Data.GetDataPresent(DataFormats.StringFormat)) { string dataString = (string)e.Data.GetData(DataFormats.StringFormat); if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey)) { e.Effects = DragDropEffects.Copy; } else { e.Effects = DragDropEffects.Move; } } e.Handled = true; } protected override void OnDragLeave(DragEventArgs e) { base.OnDragLeave(e); MyBox.Children.Clear(); foreach (UIElement item in collections) { MyBox.Children.Add(item); } } private UIElementCollection collections; }
然后主窗口程序:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MyCanvas_LeftButtonDown(object sender, MouseButtonEventArgs e) { FrameworkElement start = sender as FrameworkElement; FrameworkElement source = e.Source as FrameworkElement; FrameworkElement originalsource = e.OriginalSource as FrameworkElement; this.TargetCanvas = e.Source as FrameworkElement; this.ClickPoint = e.GetPosition(MyCanvas); this.MyText.Text = "StartPoint.X:" + this.ClickPoint.X + "StartPoint.Y" + this.ClickPoint.Y; OriginalLeft = Canvas.GetLeft(TargetCanvas); OriginalTop = Canvas.GetTop(TargetCanvas); } private void MyCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { this.TargetCanvas = null; } private void MyCanvas_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { this.DropPoint = e.GetPosition(MyCanvas); Canvas.SetLeft(this.TargetCanvas,OriginalLeft+this.DropPoint.X-this.ClickPoint.X); Canvas.SetTop(this.TargetCanvas,OriginalTop+this.DropPoint.Y-this.ClickPoint.Y); } } private FrameworkElement TargetCanvas; private TextBlock SelectTextBlock; private Point ClickPoint; private Point DropPoint; private double OriginalLeft; private double OriginalTop; }