在WPF中使用MVVM拖动鼠标时绘制矩形

下面是我的xaml。 我在canvas里面有一个图像。 我想在图像上拖动鼠标时在图像上绘制矩形。 我在WPF中成功完成了它。 但现在我想在MVVM中做到这一点。 我没有在代码中使用事件处理程序,而是希望将它们放在我的ViewModel中。 我正在使用MVVM Foundation来实现MVVM。 以下是MVVM Foundation的链接。 http://sofzh.miximages.com/c%23/CapturedImage.png” MouseDown=”imgCamera_MouseDown” MouseMove=”imgCamera_MouseMove” MouseUp=”imgCamera_MouseUp” />

用代码写的代码

 // This is the rectangle to be shown when mouse is dragged on camera image. private Point startPoint; private Rectangle rectSelectArea; ///  /// ///  ///  ///  private void imgCamera_MouseDown(object sender, MouseButtonEventArgs e) { startPoint = e.GetPosition(cnvImage); // Remove the drawn rectanglke if any. // At a time only one rectangle should be there if (rectSelectArea != null) cnvImage.Children.Remove(rectSelectArea); // Initialize the rectangle. // Set border color and width rectSelectArea = new Rectangle { Stroke = Brushes.LightBlue, StrokeThickness = 2 }; Canvas.SetLeft(rectSelectArea, startPoint.X); Canvas.SetTop(rectSelectArea, startPoint.X); cnvImage.Children.Add(rectSelectArea); } ///  /// ///  ///  ///  private void imgCamera_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Released || rectSelectArea == null) return; var pos = e.GetPosition(cnvImage); // Set the position of rectangle var x = Math.Min(pos.X, startPoint.X); var y = Math.Min(pos.Y, startPoint.Y); // Set the dimenssion of the rectangle var w = Math.Max(pos.X, startPoint.X) - x; var h = Math.Max(pos.Y, startPoint.Y) - y; rectSelectArea.Width = w; rectSelectArea.Height = h; Canvas.SetLeft(rectSelectArea, x); Canvas.SetTop(rectSelectArea, y); } ///  /// ///  ///  ///  private void imgCamera_MouseUp(object sender, MouseButtonEventArgs e) { rectSelectArea = null; } 

我需要知道在viewmodel中需要写什么,因此XAML需要进行哪些更改。

提前致谢。

可以在本文/项目中找到实现resize的非常简洁的方法。 如果您使用那里实现的DesignerItemStyle,您可以像这样添加绑定支持:

  

这样就可以在纯XAML中resize,并使用标准的WPF方法将值传递给底层的ViewModel。

请参阅以下链接访问代码项目!

http://www.codeproject.com/Articles/148503/Simple-Drag-Selection-in-WPF