[英]Draw rectangle when mouse dragged using MVVM in WPF
下面是我的xaml。 我在画布里面有一个图像。 我想在图像上拖动鼠标时在图像上绘制矩形。 我在WPF中成功完成了它。 但现在我想在MVVM中做到这一点。 我没有在代码中使用事件处理程序,而是希望将它们放在我的ViewModel中。 我正在使用MVVM Foundation来实现MVVM。 以下是MVVM Foundation的链接。 http://mvvmfoundation.codeplex.com/
任何帮助都非常感谢。
XAML
<Canvas Name="cnvImage">
<Image Height="348" HorizontalAlignment="Left" Margin="12,39,0,0" Name="imgPreview"
Stretch="Fill" VerticalAlignment="Top" Width="443"
Source="/Images/CapturedImage.png"
MouseDown="imgCamera_MouseDown" MouseMove="imgCamera_MouseMove" MouseUp="imgCamera_MouseUp" />
</Canvas>
用代码写的代码
// This is the rectangle to be shown when mouse is dragged on camera image.
private Point startPoint;
private Rectangle rectSelectArea;
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imgCamera_MouseUp(object sender, MouseButtonEventArgs e)
{
rectSelectArea = null;
}
我需要知道在viewmodel中需要写什么,因此需要在XAML中进行哪些更改。
提前致谢。
可以在本文/项目中找到实现调整大小的非常简洁的方法。 如果您使用那里实现的DesignerItemStyle,您可以像这样添加绑定支持:
<Rectangle Style="{StaticResource DesignerItemStyle}"
Canvas.Left="{Binding Path=Leftoffset, Mode=TwoWay}"
Canvas.Top="{Binding Path=Topoffset, Mode=TwoWay}"
Width="{Binding Path=Width, Mode=TwoWay}"
Height="{Binding Path=Height, Mode=TwoWay}">
这样就可以在纯XAML中调整大小,并使用标准的WPF方法将值传递给底层的ViewModel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.