Dưới đây là xaml của tôi. Tôi có một hình ảnh bên trong một khung hình. Tôi muốn vẽ hình chữ nhật trên hình ảnh khi chuột được kéo trên hình ảnh. Tôi đã thành công trong WPF. Nhưng bây giờ tôi muốn làm điều đó trong MVVM. Thay vì có các trình xử lý sự kiện trong mã phía sau, tôi muốn có chúng trong ViewModel của mình. Tôi đang sử dụng Quỹ MVVM để triển khai MVVM. Dưới đây là một liên kết đến MVVM Foundation. http://mvvmfoundation.codeplex.com/Vẽ hình chữ nhật khi chuột kéo bằng MVVM trong WPF
Mọi trợ giúp đều được đánh giá cao.
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>
Mã được viết bằng mã đằng sau
// 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;
}
Tôi cần phải biết những gì tôi cần phải viết trong viewmodel của tôi và theo đó những thay đổi nào được yêu cầu trong XAML.
Xin cảm ơn trước.
Đừng quên MVVM có nghĩa là tách lớp. Khả năng vẽ một hình chữ nhật có vẻ khá đặc trưng cho giao diện người dùng, vì vậy tôi sẽ không gặp vấn đề gì khi vẽ nó trong đoạn mã sau và chuyển hình chữ nhật hoàn chỉnh đến lớp dữ liệu ('ViewModel') khi nút chuột được phát hành. – Rachel