在WPF中使用MVVM拖动鼠标时绘制矩形
本文关键字:鼠标 绘制 拖动 MVVM WPF | 更新日期: 2023-09-27 18:12:50
下面是我的xaml。我在画布中有一个图像。当鼠标在图像上拖动时,我想在图像上画一个矩形。我在WPF中成功做到了。但现在我想用MVVM来做。而不是在代码后面的事件处理程序,我想让他们在我的ViewModel。我使用MVVM基础实现MVVM。下面是MVVM基金会的链接。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;
}
我需要知道我需要在我的视图模型中写什么,以及相应地在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方法将值获取到底层的ViewModels
参考下面给出的链接访问Code项目!
http://www.codeproject.com/Articles/148503/Simple-Drag-Selection-in-WPF?