I have a custom WPF control which consist of single TextBox
<UserControl HorizontalAlignment="Left" x:Class="WPFDiagramDesignerControl.Components.UcWBSBlock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="100" Width="100" IsEnabled="True">
<Grid >
<TextBox x:Name="txtBox" IsEnabled="True" Background="AntiqueWhite" Margin="10,10,10,10" TextWrapping="Wrap"> </TextBox>
</Grid>
</UserControl>
The control is placed on Canvas called MyDesigner.
I want to move my control on canvas only if I click on textbox and move mouse. I don't want to move control when I click on margin between borders of control and textbox.
I started writting a code and it looks like that
public partial class UcWBSBlock : UserControl
{
bool textChanged = false;
bool isClicked = false;
Point startPoint;
DesignerItem parentItem;
DesignerCanvas parentCanvas;
public UcWBSBlock()
{
InitializeComponent();
txtBox.MouseDoubleClick+=new MouseButtonEventHandler(txtBox_MouseDoubleClick);
txtBox.MouseMove+=new MouseEventHandler(txtBox_MouseMove);
txtBox.PreviewMouseDown+=new MouseButtonEventHandler(txtBox_PreviewMouseDown);
txtBox.PreviewMouseUp+=new MouseButtonEventHandler(txtBox_PreviewMouseUp);
txtBox.Cursor = Cursors.SizeAll;
}
private void txtBox_MouseMove(object sender, RoutedEventArgs e)
{
if (isClicked)
{
Point mousePos = Mouse.GetPosition(parentCanvas);
parentItem = this.Parent as DesignerItem;
parentCanvas = parentItem.Parent as DesignerCanvas;
Point relativePosition = Mouse.GetPosition(parentCanvas);
DesignerCanvas.SetLeft(parentItem,DesignerCanvas.GetLeft(parentItem) - (startPoint.X - mousePos.X));
DesignerCanvas.SetTop(parentItem, DesignerCanvas.GetTop(parentItem) - (startPoint.Y - mousePos.Y));
}
}
private void txtBox_PreviewMouseDown(object sender, RoutedEventArgs e)
{
if (!isClicked)
{
isClicked = true;
parentItem = this.Parent as DesignerItem;
parentCanvas = parentItem.Parent as DesignerCanvas;
startPoint = Mouse.GetPosition(parentCanvas);
}
}
private void txtBox_PreviewMouseUp(object sender, RoutedEventArgs e)
{
isClicked = false;
}
}
}
However my control doesn't move :( What did I do wrong ?? It's hard to debug this :)
you are setting the left/top of the parent item, not your control:
DesignerCanvas.SetLeft(parentItem,DesignerCanvas.GetLeft(parentItem) - (startPoint.X - mousePos.X));
DesignerCanvas.SetTop(parentItem, DesignerCanvas.GetTop(parentItem) - (startPoint.Y - mousePos.Y));
should (probably) be like this:
DesignerCanvas.SetLeft(this,DesignerCanvas.GetLeft(this) - (startPoint.X - mousePos.X));
DesignerCanvas.SetTop(this, DesignerCanvas.GetTop(this) - (startPoint.Y - mousePos.Y));
Related
I am struggling with making both touch events and manipulation work properly in a WPF project. I have a ScrollViewer which contains a picture and I would like to scroll both horizontally and vertically using a swipe gestures. Additionally, I would like to zoom in/out in the center of the pinch gesture. The code below achieves what I wish, but it has the following problems:
Sometimes the scrolling is laggy;
The scrolling does not work on the first try, only when attempting the same gesture a second time;
The zoom in/out does not work on the first try, only when attempting the same gesture a second time.
I enabled the IsManipulationEnabled and I implemented the code for zoom in/out functionality. However, I was not able to combine it with the scrolling functionality (by setting the PanningMode in the ScrollViewer only). Therefore, I created a custom control which inherits from Image control and I overwritten the OnTouchDown and OnTouchUp event handlers. Basically, what I am doing in these overwritten handlers is counting the number of touches on the screen and enabling/disabling manipulation. I also tried setting the PanningMode for the ScrollViewer, but it did not do the trick.
Below is the XAML:
<Grid>
<ScrollViewer
x:Name="ScrollViewerParent"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
PanningMode="Both">
<local:CustomImage
x:Name="MainImage"
Source="{Binding Source={x:Static local:Constants.ImagePath}}"
IsManipulationEnabled="True"
ManipulationStarting="MainImage_ManipulationStarting"
ManipulationDelta="MainImage_ManipulationDelta">
</local:CustomImage>
</ScrollViewer>
</Grid>
Here is the code-behind:
public partial class MainWindow : Window
{
private void MainImage_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
e.ManipulationContainer = ScrollViewerParent;
e.Handled = true;
}
private void MainImage_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
var matrix = MainImage.LayoutTransform.Value;
Point? centerOfPinch = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, ScrollViewerParent);
if (centerOfPinch == null)
{
return;
}
var deltaManipulation = e.DeltaManipulation;
matrix.ScaleAt(deltaManipulation.Scale.X, deltaManipulation.Scale.Y, centerOfPinch.Value.X, centerOfPinch.Value.Y);
MainImage.LayoutTransform = new MatrixTransform(matrix);
Point? originOfManipulation = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, MainImage);
double scrollViewerOffsetX = ScrollViewerParent.HorizontalOffset;
double scrollViewerOffsetY = ScrollViewerParent.VerticalOffset;
double pointMovedOnXOffset = originOfManipulation.Value.X - originOfManipulation.Value.X * deltaManipulation.Scale.X;
double pointMovedOnYOffset = originOfManipulation.Value.Y - originOfManipulation.Value.Y * deltaManipulation.Scale.Y;
double multiplicatorX = ScrollViewerParent.ExtentWidth / MainImage.ActualWidth;
double multiplicatorY = ScrollViewerParent.ExtentHeight / MainImage.ActualHeight;
ScrollViewerParent.ScrollToHorizontalOffset(scrollViewerOffsetX - pointMovedOnXOffset * multiplicatorX);
ScrollViewerParent.ScrollToVerticalOffset(scrollViewerOffsetY - pointMovedOnYOffset * multiplicatorY);
e.Handled = true;
}
}
The XAML for the custom control:
<Style TargetType="{x:Type local:CustomImage}" />
Here is where I override the OnTouchDown and OnTouchUp event handlers:
public class CustomImage : Image
{
private volatile int nrOfTouchPoints;
private volatile bool isManipulationReset;
private object mutex = new object();
static CustomImage()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomImage), new FrameworkPropertyMetadata(typeof(CustomImage)));
}
protected override void OnTouchDown(TouchEventArgs e)
{
lock (mutex)
{
nrOfTouchPoints++;
if (nrOfTouchPoints >= 2)
{
IsManipulationEnabled = true;
isManipulationReset = false;
}
}
base.OnTouchDown(e);
}
protected override void OnTouchUp(TouchEventArgs e)
{
lock (mutex)
{
if (!isManipulationReset)
{
IsManipulationEnabled = false;
isManipulationReset = true;
nrOfTouchPoints = 0;
}
}
base.OnTouchUp(e);
}
}
What I expect from this code is the following:
When using one finger to swipe horizontally or vertically across the touchscreen, the image should be scrolled accordingly;
When I use a pinch gesture on the touch screen, the image should be zoomed in/out in the center of the pinch.
Fortunately, I managed to find the perfect solution. Therefore, I am going to post the answer in the case that someone is working on a similar problem and needs some help.
What I did:
Got rid of the custom control as it was not necessary;
Create a field which counts the number of the touch points;
Implemented the TouchDown event handler, which increases the number of touch points by 1 (this method is called each time there is a touch down gesture on the device);
Implemented the TouchUp event handler, which decreases the number of touch points by 1 (this method is called each time there is a touch up gesture on the device);
In the Image_ManipulationDelta event handler, I check the number of touch points:
if the number of touch points < 2, then the translation value is added to the current offset of the scrollbars, thus achieving scrolling;
otherwise, the center of the pinch is calculated and a scale gesture is applied.
Here is the full XAML:
<Grid
x:Name="GridParent">
<ScrollViewer
x:Name="ScrollViewerParent"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
PanningMode="Both">
<Image
x:Name="MainImage"
Source="{Binding Source={x:Static local:Constants.ImagePath}}"
IsManipulationEnabled="True"
TouchDown="MainImage_TouchDown"
TouchUp="MainImage_TouchUp"
ManipulationDelta="Image_ManipulationDelta"
ManipulationStarting="Image_ManipulationStarting"/>
</ScrollViewer>
</Grid>
Here is the entire code discussed above:
public partial class MainWindow : Window
{
private volatile int nrOfTouchPoints;
private object mutex = new object();
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
e.ManipulationContainer = ScrollViewerParent;
e.Handled = true;
}
private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
int nrOfPoints = 0;
lock (mutex)
{
nrOfPoints = nrOfTouchPoints;
}
if (nrOfPoints >= 2)
{
DataLogger.LogActionDescription($"Executed {nameof(Image_ManipulationDelta)}");
var matrix = MainImage.LayoutTransform.Value;
Point? centerOfPinch = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, ScrollViewerParent);
if (centerOfPinch == null)
{
return;
}
var deltaManipulation = e.DeltaManipulation;
matrix.ScaleAt(deltaManipulation.Scale.X, deltaManipulation.Scale.Y, centerOfPinch.Value.X, centerOfPinch.Value.Y);
MainImage.LayoutTransform = new MatrixTransform(matrix);
Point? originOfManipulation = (e.ManipulationContainer as FrameworkElement)?.TranslatePoint(e.ManipulationOrigin, MainImage);
double scrollViewerOffsetX = ScrollViewerParent.HorizontalOffset;
double scrollViewerOffsetY = ScrollViewerParent.VerticalOffset;
double pointMovedOnXOffset = originOfManipulation.Value.X - originOfManipulation.Value.X * deltaManipulation.Scale.X;
double pointMovedOnYOffset = originOfManipulation.Value.Y - originOfManipulation.Value.Y * deltaManipulation.Scale.Y;
double multiplicatorX = ScrollViewerParent.ExtentWidth / MainImage.ActualWidth;
double multiplicatorY = ScrollViewerParent.ExtentHeight / MainImage.ActualHeight;
ScrollViewerParent.ScrollToHorizontalOffset(scrollViewerOffsetX - pointMovedOnXOffset * multiplicatorX);
ScrollViewerParent.ScrollToVerticalOffset(scrollViewerOffsetY - pointMovedOnYOffset * multiplicatorY);
e.Handled = true;
}
else
{
ScrollViewerParent.ScrollToHorizontalOffset(ScrollViewerParent.HorizontalOffset - e.DeltaManipulation.Translation.X);
ScrollViewerParent.ScrollToVerticalOffset(ScrollViewerParent.VerticalOffset - e.DeltaManipulation.Translation.Y);
}
}
private void MainImage_TouchDown(object sender, TouchEventArgs e)
{
lock (mutex)
{
nrOfTouchPoints++;
}
}
private void MainImage_TouchUp(object sender, TouchEventArgs e)
{
lock (mutex)
{
nrOfTouchPoints--;
}
}
}
}
I am very new to C# and WPF and would to create a WPF application that draws shapes with a button. The shapes then need to be able to move around the canvas. When I create a shape in the XAML it moves. However I cannot get the one created by the button to move. Could anyone please assist? Below are the XAML and code that i am using.
XAML:
<Window x:Class="All_test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas x:Name="canvas" >
<Button Content="Button" Canvas.Left="250" Canvas.Top="260" Width="75" Click="Button_Click_1" />
<Rectangle x:Name="rect"
Height="100" Width ="100" Fill="red"
MouseLeftButtonDown="rect_MouseLeftButtonDown"
MouseLeftButtonUp="rect_MouseLeftButtonUp"
MouseMove="rect_MouseMove"
Canvas.Left="342" Canvas.Top="110" />
</Canvas>
This is the code I am using to move the red square drawn in XAML. How can I do the same for the green one created by the button?
public partial class MainWindow : Window
{
private bool _isRectDragInProg;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Rectangle rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Green);
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Height = 100;
rect.Width = 100;
rect.StrokeThickness = 4;
canvas.Children.Add(rect);
InitializeComponent();
}
private void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_isRectDragInProg = true;
rect.CaptureMouse();
}
private void rect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_isRectDragInProg = false;
rect.ReleaseMouseCapture();
}
private void rect_MouseMove(object sender, MouseEventArgs e)
{
if (!_isRectDragInProg) return;
// get the position of the mouse relative to the Canvas
var mousePos = e.GetPosition(canvas);
// center the rect on the mouse
double left = mousePos.X - (rect.ActualWidth / 2);
double top = mousePos.Y - (rect.ActualHeight / 2);
Canvas.SetLeft(rect, left);
Canvas.SetTop(rect, top);
}
You should bind the mouse events for this Rectangle:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Rectangle rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Green);
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Height = 100;
rect.Width = 100;
rect.StrokeThickness = 4;
// here
rect.MouseLeftButtonDown += rect_MouseLeftButtonDown;
rect.MouseLeftButtonUp += rect_MouseLeftButtonUp;
rect.MouseMove += rect_MouseMove;
canvas.Children.Add(rect);
// InitializeComponent(); <--- lose the InitializeComponent here, that's should only be called ones.. (in the constructor)
}
Recommendations:
Use the sender parameter to get the current Rectangle.
You can lose the _isRectDragInProg boolean... use the IsMouseCaptured property instead.
For example:
private void rect_MouseMove(object sender, MouseEventArgs e)
{
var rect = (Rectangle)sender;
if (!rect.IsMouseCaptured) return;
// get the position of the mouse relative to the Canvas
var mousePos = e.GetPosition(canvas);
// center the rect on the mouse
double left = mousePos.X - (rect.ActualWidth / 2);
double top = mousePos.Y - (rect.ActualHeight / 2);
Canvas.SetLeft(rect, left);
Canvas.SetTop(rect, top);
}
I need to move an image over a canvas on tap and slide. How can I achieve this. I tried the following. The image is moving but not as the user moves it.
XAML
<Canvas Background="White">
<Image Name="img" Width="200" Height="200" Source="Assets/11.png" ManipulationMode="All" ManipulationStarted="img_ManipulationStarted" ManipulationDelta="img_ManipulationDelta"/>
</Canvas>
C#
private Point initialPt;
private void img_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
initialPt = e.Position;
}
private void img_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
Point currentPt = e.Position;
double x = currentPt.X - initialPt.X;
double y = currentPt.Y - initialPt.Y;
if (x != 0 || y != 0)
{
TranslateTransform posTransform = new TranslateTransform();
posTransform.X = currentPt.X;
posTransform.Y = currentPt.Y;
img.RenderTransform = posTransform;
e.Complete();
}
}
Instead of using a TranslateTransform, you should directly set the absolute position in the canvas, so you have to bind the ManipulationDelta event to the Canvas, and detect if the point of impact is inside of the image.
<Canvas Background="White" ManipulationMode="All" ManipulationDelta="canvas_ManipulationDelta">
<Image Name="img" Width="200" Height="200" Source="Assets/11.png"/>
</Canvas>
Here is the new event handling function:
private void canvas_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
if ((e.Position.X > Canvas.GetLeft(img) && e.Position.X < Canvas.GetLeft(img) + img.Width)
|| (e.Position.Y > Canvas.GetTop(img) && e.Position.Y < Canvas.GetTop(img) + img.Height)) {
{
Canvas.SetLeft(img, e.Position.X);
Canvas.SetTop(img, e.Position.Y);
}
}
Simple as pie. You can remove initialPt and img_ManipulationStarted.
Being new to WPF and MVVM I searched everywhere to find a good answer to my problem. I'm creating a cropping application but I'm trying to migrate the code behind codes to a view model. I was able to bind my mouse button event by using blends interactivity triggers code is below:
<Grid x:Name="GridLoadedImage" HorizontalAlignment="Left" VerticalAlignment="Top">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding MouseLeftButtonUpCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseMove">
<i:InvokeCommandAction Command="{Binding MouseMoveCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=slider1, Path=Value}" ScaleY="{Binding ElementName=slider1, Path=Value}"/>
</Grid.LayoutTransform>
<Image x:Name="LoadedImage" Margin="10" Source="{Binding ImagePath}"/>
<Canvas x:Name="BackPanel" Margin="10">
<Rectangle x:Name="selectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed"/>
</Canvas>
</Grid>
Now my dilema is how to migrate the actual code i used from my code behind which is shown below:
private void LoadedImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (isDragging == false)
{
anchorPoint.X = e.GetPosition(BackPanel).X;
anchorPoint.Y = e.GetPosition(BackPanel).Y;
Canvas.SetZIndex(selectionRectangle, BackPanel.Children.Count);
isDragging = true;
BackPanel.Cursor = Cursors.Cross;
}
}
private void LoadedImage_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
double x = e.GetPosition(BackPanel).X;
double y = e.GetPosition(BackPanel).Y;
selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);
if (selectionRectangle.Visibility != Visibility.Visible)
selectionRectangle.Visibility = Visibility.Visible;
}
}
private void LoadedImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (isDragging)
{
isDragging = false;
if (selectionRectangle.Width > 0)
{
Crop.IsEnabled = true;
Cut.IsEnabled = true;
BackPanel.Cursor = Cursors.Arrow;
}
}
}
As you can see I would need to be able to access the x and y coordinates as well as the width and height of the rectangle (which is named selection rectangle). I was thinking of creating the canvas and rectangle inside my viewmodel but that would be against the mvvm structure. I read that I could use attached properties but not familiar with it. What is the best possible way of handling this with respect to MVVM pattern. Currently I'm reading a book by Adan Nathan WPF unleashed 4 which is a great book for beginners like me but i cant seem to find anything that relates to my problem. Thanks for any help
I do have a view model code for my mouse event:
#region MouseLeftButtonDown
private bool isDragging = false;
private Point anchorPoint = new Point();
private ICommand _mouseLeftButtonDownCommand;
public ICommand MouseLeftButtonDownCommand
{
get
{
if (_mouseLeftButtonDownCommand == null)
{
_mouseLeftButtonDownCommand = new RelayCommand(param => MouseLeftButtonDown());
}
return _mouseLeftButtonDownCommand;
}
}
public void MouseLeftButtonDown()
{
if (isDragging == false)
{
MessageBox.Show("THis is Mouse Down");
//anchorPoint.X = e.GetPosition(BackPanel).X;
//anchorPoint.Y = e.GetPosition(BackPanel).Y;
isDragging = true;
}
}
#endregion
#region MouseLeftButtonUp
private ICommand _mouseLeftButtonUpCommand;
public ICommand MouseLeftButtonUpCommand
{
get
{
if (_mouseLeftButtonUpCommand == null)
{
_mouseLeftButtonUpCommand = new RelayCommand(param => MouseLeftButtonUp((MouseButtonEventArgs)param));
}
return _mouseLeftButtonUpCommand;
}
}
public void MouseLeftButtonUp(MouseButtonEventArgs e)
{
if (isDragging)
{
MessageBox.Show(e.Source.ToString());
isDragging = false;
//if (selectionRectangle.Width > 0)
//{
// Crop.IsEnabled = true;
// Cut.IsEnabled = true;
// BackPanel.Cursor = Cursors.Arrow;
//}
}
}
#endregion
#region MouseMove
private ICommand _mouseMoveCommand;
public ICommand MouseMoveCommand
{
get
{
if (_mouseMoveCommand == null)
{
_mouseMoveCommand = new RelayCommand(param => MouseMove());
}
return _mouseMoveCommand;
}
}
public void MouseMove()
{
if (isDragging)
{
//MessageBox.Show("THis is Mouse Move");
//double x = e.GetPosition(BackPanel).X;
//double y = e.GetPosition(BackPanel).Y;
//selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
//selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
//selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
//selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);
//if (selectionRectangle.Visibility != Visibility.Visible)
// selectionRectangle.Visibility = Visibility.Visible;
}
}
#endregion
I just commented the actual code and replace it with message boxes just to test if my trigger work which it does. This 3 functions once I figure out how to make it work would draw the cropping rectangle on top of the imaged being cropped. I do have a crop button the will be enabled once the rectangle is completed and this button will be bound to another function that would be the actual cropping function.
That's more simple than you may have thought.
What you are doing is an UserControl which userdefined behaviour. So rather than putting that XAML into your Page/View, you implement your own Control which derives from UserControl and implement your code as you have in your code-behind.
Since you are making a custom control, you don't have to follow MVVM for it. In fact, MVVM patter for user controls is discouraged. In your custom control you define may define a Dependency Property which holds an Object of type "SelectionRect" (you shouldn't be using Rect as it's a struct and it doesn't work well with databinding, as it creates a new copy of it each time it changes).
public class CropControl : UserControl
{
public Rect Selection
{
get { return (Rect)GetValue(SelectionProperty); }
set { SetValue(SelectionProperty, value); }
}
public static readonly DependencyProperty SelectionProperty =
DependencyProperty.Register("Selection", typeof(Rect), typeof(CropControl), new PropertyMetadata(default(Rect)));
// this is used, to react on changes from ViewModel. If you assign a
// new Rect in your ViewModel you will have to redraw your Rect here
private static void OnSelectionChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
{
Rect newRect = (Rect)e.NewValue;
Rectangle selectionRectangle = d as Rectangle;
if(selectionRectangle!=null)
return;
selectionRectangle.SetValue(Canvas.LeftProperty, newRect.X);
selectionRectangle.SetValue(Canvas.TopProperty, newRect.Y);
selectionRectangle.Width = newRect.Width;
selectionRectangle.Height = newRect.Height;
}
private void LoadedImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (isDragging == false)
{
anchorPoint.X = e.GetPosition(BackPanel).X;
anchorPoint.Y = e.GetPosition(BackPanel).Y;
Canvas.SetZIndex(selectionRectangle, BackPanel.Children.Count);
isDragging = true;
BackPanel.Cursor = Cursors.Cross;
}
}
private void LoadedImage_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
double x = e.GetPosition(BackPanel).X;
double y = e.GetPosition(BackPanel).Y;
selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);
if (selectionRectangle.Visibility != Visibility.Visible)
selectionRectangle.Visibility = Visibility.Visible;
}
}
private void LoadedImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (isDragging)
{
isDragging = false;
if (selectionRectangle.Width > 0)
{
Crop.IsEnabled = true;
Cut.IsEnabled = true;
BackPanel.Cursor = Cursors.Arrow;
}
// Set the Selection to the new rect, when the mouse button has been released
Selection = new Rect(
selectionRectangle.GetValue(Canvas.LeftProperty),
selectionRectangle.GetValue(Canvas.TopProperty),
selectionRectangle.Width,
selectionRectangle.Height);
}
}
}
Notice the only changes were to add Selection = new Rect(...) and the Dependency Property.
Then you can bind it in XAML.
<my:CropControl Selection="{Binding Selection,Mode=TwoWay}"/>
Update:
Your ViewModel would look something like
public class MyViewModel : ViewModel
{
private Rect selection;
public Rect Selection
{
get
{
return selection;
}
set
{
selection = value;
// Or whatever the name of your framework/implementation the method is called
OnPropertyChanged("Selection");
// Cause ICommands to reevaluate their CanExecute methods
CommandManager.InvalidateRequerySuggested();
}
}
private ICommand cropCommand;
public ICommand CropCommand {
get
{
if(cropCommand==null)
cropCommand = new RelayCommand(Crop, () => Selection.Width > 0); // only allow execution when Selection width > 0
return cropCommand;
}
}
public void Crop()
{
// Get a copy of the selection in case it changes during execution
Rect cropSelection = Selection;
// use it to crop your image
...
}
}
Drawing Selection = View Logic (So View)
Cropping with a Rect given by CropControl => Presentation/Business Logic (so ViewModel)
Doing so, allows you to reuse your CropControl in other applications. If you put your "selectionRect" drawing code into your ViewModel (which may be possible, but causes hard to read and maintain code), then you can't reuse it in other application, since your ViewModels are specific to your application.
Hope that helps.
MVVM means separating View from ViewModel. The example you give is typically a View only code.
Your example seems to be a kind of selection tool, I deduce you want to get the selected content back, or at least the cropping coordinates. So the best is to transform your code in a custom control exposing a Rect DependencyProperty for the crop coordinates, and in your view model, you should expose a Rect property holding the cropping rectangle coordinates, and then Bind it to your cropping control DepencyProperty.
The view is about interacting with visual aspects. The ViewModel is about holding and working with the data used by the view.
Why does not the MouseLeftButtonUp on my Canvas fire in my WPF app?
Here is the XAML:
<Grid Height="300" Width="400">
<Canvas Name="canvas" MouseMove="canvas_MouseMove" MouseLeftButtonUp="canvas_MouseLeftButtonUp" Background="LightGray"/>
</Grid>
And the code:
private bool hasClicked = false;
public Window1()
{
InitializeComponent();
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (!this.hasClicked)
{
this.Cursor = Cursors.None;
this.canvas.Children.Clear();
this.insertRectangle(false);
}
}
private void insertRectangle(bool filled)
{
Rectangle rect = createRect(filled);
Point pos = Mouse.GetPosition(this.canvas);
Canvas.SetLeft(rect, pos.X);
Canvas.SetTop(rect, pos.Y);
this.canvas.Children.Add(rect);
}
private Rectangle createRect(bool fill)
{
Rectangle rect = new Rectangle();
rect.Height = 50;
rect.Width = 120;
if (fill)
{
rect.Fill = new SolidColorBrush(Colors.Green);
}
else
{
rect.Stroke = new SolidColorBrush(Colors.Green);
}
return rect;
}
private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.hasClicked = true;
this.insertRectangle(true);
this.Cursor = Cursors.Arrow;
}
Edit: I have tried adding a background colour to the canvas, but still the event is not fired. It seems like the MouseMove somehow overrides the MouseLeftButtonUp.
Edit2: If I remove the MouseMove event, mouseLeftButtonUp will fire.
Edit3: Bigger code example.
In the insertRectangle method, if I use
Canvas.SetTop(rect, 50);
instead of
Canvas.SetTop(rect, pos.Y);
the events fires just fine.
If you don't set a Background on the canvas, it doesn't seem to pay attention to your mouse events.
Try:
<Grid>
<Canvas Name="canvas"
MouseMove="canvas_MouseMove"
MouseLeftButtonUp="canvas_MouseLeftButtonUp"
Background="White" />
</Grid>
By not clearing the canvas, but instead moving the preview rectangle in the mouseMove method solved the problem.