[英]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.