I am new to WPF I want to scale ellipse by selecting its stroke. I have set IsManipulationEnabled=true but an event not triggering. Below is my code
<Path Stretch="Fill" Stroke="Black" ManipulationDelta="Path_ManipulationDelta"
IsManipulationEnabled="True" StrokeThickness="4">
<Path.Data>
<EllipseGeometry Center="0,0" RadiusX="200" RadiusY="200"/>
</Path.Data>
</Path>
Please Help.enter image description here
Here is some code that may give you some ideas:
In this sample, I'm using some basic mouse events MouseDown, MouseMove, and MouseUp so that I can detect when a user clicks on the Path, and when they start to drag the mouse.
XAML
<Window x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp4"
Title="MainWindow"
Width="800"
Height="450"
UseLayoutRounding="True">
<Grid>
<Canvas x:Name="Canvas">
<Path x:Name="CirclePath"
MouseDown="OnMouseDown"
MouseMove="OnMouseMove"
MouseUp="OnMouseUp"
Stretch="Fill"
Stroke="Black"
StrokeThickness="4">
<Path.Data>
<EllipseGeometry x:Name="EllipseGeometry"
Center="0,0"
RadiusX="100"
RadiusY="100" />
</Path.Data>
</Path>
</Canvas>
</Grid>
</Window>
In the OnMouseDown handler, I check to see if the left mouse button is down and then I capture the mouse and get the position of the mouse relative to the Canvas.
Next, in the OnMouseMove handler, if the left button is still down - the user is dragging - I get the new mouse position and calculate the offset based on the old mouse position. Then I update the EllipseGeometry to reflect the mouse offset.
Finally, in the OnMouseUp handler, I release the mouse capture.
Code-Behind
using System.Windows;
using System.Windows.Input;
namespace WpfApp4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Point oldMousePosition;
public MainWindow()
{
InitializeComponent();
}
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
if(e.ChangedButton != MouseButton.Left) return;
Mouse.Capture(CirclePath);
oldMousePosition = e.GetPosition(Canvas);
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed) return;
var newMousePosition = e.GetPosition(Canvas);
var offset = newMousePosition - oldMousePosition;
EllipseGeometry.RadiusX += offset.X / 2;
EllipseGeometry.RadiusY += offset.Y / 2;
oldMousePosition = newMousePosition;
}
private void OnMouseUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
}
}
}
I hope this helps.
XAML
XAML
<Window x:Class="WidgetWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WidgetWpf"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Viewbox>
<Grid Name="MainGrid">
<Ellipse x:Name="DottedCircle" Width="200" Height="200" Stroke="White" StrokeThickness="2" Opacity="0.90" StrokeDashArray="4 4"
MouseDown="DottedCircle_MouseDown"
MouseMove="DottedCircle_MouseMove"
MouseUp="DottedCircle_MouseUp"
MouseEnter="DottedCircle_MouseEnter"
MouseLeave="DottedCircle_MouseLeave"
/>
</Grid>
</Viewbox>
</Window>
//Here is my code behind
public partial class MainWindow : Window
{
#region Variables
MatrixTransform transform;
Point OldMousePosition;
Point NewMousePosition;
double[] Dimensions = new double[2];
Rect rect = new Rect();
bool IsResizeMode;
bool IsDragAndDropMode;
#endregion
public MainWindow()
{
InitializeComponent();
}
private void DottedCircle_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left) return;
Mouse.Capture(DottedCircle);
OldMousePosition = e.GetPosition(MainGrid);
}
private void DottedCircle_MouseMove(object sender, MouseEventArgs e)
{
DottedCircle.ToolTip = e.GetPosition(MainGrid);
if (e.LeftButton != MouseButtonState.Pressed) return;
var NewMousePosition = e.GetPosition(MainGrid);
var offset = NewMousePosition-OldMousePosition;
#region working by co-ordinate
//get center of grid
double dicisionPoint=0.0 ;
double CP_X = MainGrid.ActualWidth / 2;
double CP_Y = MainGrid.ActualHeight / 2;
//1 st co-ordinate
if(NewMousePosition.X>CP_X && NewMousePosition.Y<CP_Y)
{
dicisionPoint = offset.X;
}
//2nd cordinate
else if (NewMousePosition.X < CP_X && NewMousePosition.Y < CP_Y)
{
dicisionPoint = -offset.X;
}
else if (NewMousePosition.X < CP_X && NewMousePosition.Y > CP_Y)
{
dicisionPoint = offset.Y;
}
else if (NewMousePosition.X > CP_X && NewMousePosition.Y > CP_Y)
{
dicisionPoint = offset.Y;
}
if (DottedCircle.Width+ dicisionPoint < InnerCircle.Width)
{
DottedCircle.Fill = new SolidColorBrush(Colors.Transparent);
DottedCircle.Width += dicisionPoint;
DottedCircle.Height += dicisionPoint;
}
else if (DottedCircle.Width+ dicisionPoint>= InnerCircle.Width) { DottedCircle.Fill = new SolidColorBrush(Colors.Red); }
#endregion
OldMousePosition = NewMousePosition;
DottedCircle.ToolTip = offset.X+ "__" + offset.Y;
}
private void DottedCircle_MouseUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
DottedCircle.Style = null;
}
private void DottedCircle_MouseEnter(object sender, MouseEventArgs e)
{
DottedCircle.Stroke = new SolidColorBrush( Colors.Blue);
DottedCircle.Style = (Style)Application.Current.Resources["DiffPathStyle"];
}
private void DottedCircle_MouseLeave(object sender, MouseEventArgs e)
{
DottedCircle.Stroke = new SolidColorBrush(Colors.White);
DottedCircle.Style = null;
}
}
Related
2nd Edit
so removing the Panel.ZIndex properties from the control template resolved this issue for me, giving me 1 drop event.
including them triggers two drop events.
can any one answer me why though?
id love to know why z index ?
Original Question :
I am trying to add a custom object (state) to a canvas called MainCanvas on the MainWindow.
I am trying to drag a state object from a wrap panel and drop it onto the canvas.
the code works but there are two items being added.
I know there are two because I can move the two item around the canvas.
I have searched existing answers and added e.Handled=true, but still adds two items
I tried using Drop event and PreviewDrop Event on MainCanvas, no difference.
Cam someone help as to how I can make it so that only 1 item gets added?
the maincanvas exists at design time
a new state is created at runtime at the drop event.
Here is the OnMouseMove handler for the state
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.LeftButton == MouseButtonState.Pressed)
{
var parent = VisualTreeHelper.GetParent(this);
if (parent as WrapPanel != null)
{
DataObject dragData = new DataObject();
dragData.SetData(DataFormats.StringFormat, this.ItemType);
DragDrop.DoDragDrop(this, dragData, DragDropEffects.Copy);
}
}
e.Handled = true;
}
Within the Code Behind I have set the following events for the canvas:
private void MainCanvas_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effects = DragDropEffects.Copy;
else
e.Effects = DragDropEffects.None;
e.Handled = true;
}
private void MainCanvas_Drop(object sender, DragEventArgs e)
{
var itemType = e.Data.GetData(typeof(string));
switch (itemType)
{
case "state":
var pos = e.GetPosition(this.MainCanvas);
State item = new State();
item.Template = (ControlTemplate)FindResource("StateViewModelControlTemplate");
this.MainCanvas.Children.Add(item);
Canvas.SetLeft(item, pos.X);
Canvas.SetTop(item, pos.Y);
e.Handled = true;
break;
default:
break;
}
e.Handled = true;
}
Finally here is the xaml for the Main Canvas
<Canvas x:Name="MainCanvas" x:Name="MainCanvas"
DockPanel.Dock="Top"
Background="#666"
Height="600"
Margin="4"
AllowDrop="True"
DragEnter="MainCanvas_DragEnter"
Drop="MainCanvas_Drop"/>
Edit:
ok so after lupus' response i went back and reconstructed everything from scratch in a separate temp project
<ControlTemplate x:Key="StateViewModelControlTemplate" TargetType="{x:Type vm:State}">
<Grid Width="100" Height="60">
<!--
If I comment out the following Thumb
the drop event will only trigger once
If i leave it in then it triggers twice
Move Thumb is derived from thumb
-->
<local:MoveThumb Panel.ZIndex="99"
x:Name="StateViewModelMoveThumb"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
Opacity="0"/>
<Border Panel.ZIndex="98"
Margin="4"
Padding="4"
BorderBrush="white"
BorderThickness="2"
CornerRadius="5">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF59C7D4" Offset="0.5"/>
<GradientStop Color="#FF075A64" Offset="0"/>
<GradientStop Color="#FF00626E" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Content="{TemplateBinding StateName}"/>
</Border>
</Grid>
</ControlTemplate>
By the way what I trying to do is very loosely based on the following article: https://www.codeproject.com/Articles/22952/WPF-Diagram-Designer-Part-1
I tried your code, and I cannot reproduce your issue. Changes:
private void MainCanvas_Drop(object sender, DragEventArgs e)
{
var itemType = e.Data.GetData(typeof(string));
switch (itemType)
{
var pos = e.GetPosition(this.MainCanvas);
Border item = new Border()
{
Width = 10,
Height = 10,
Background = Brushes.Red
};
//item.Template = (ControlTemplate)FindResource("StateViewModelControlTemplate");
this.MainCanvas.Children.Add(item);
...
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.LeftButton == MouseButtonState.Pressed)
{
DataObject dragData = new DataObject();
dragData.SetData(DataFormats.StringFormat, "state");
DragDrop.DoDragDrop(this, dragData, DragDropEffects.Copy);
}
e.Handled = true;
}
and in xaml,
<Window ...
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Canvas x:Name="MainCanvas" Grid.Column="0"
DockPanel.Dock="Top"
Background="#666"
Height="600"
Margin="4"
AllowDrop="True"
DragEnter="MainCanvas_DragEnter"
Drop="MainCanvas_Drop"/>
<Grid Grid.Column="1" Background="Red"/>
</Grid>
Have not touch the other piece of code. Everytime I drag from the Grid to the Canvas, I get one Border item at the drop position.
So maybe the problem is not in the code you posted, but in the code left out or commented.
So I eventually got this working and here is how
Here is the front end xaml on the mainwindow
<cc:DiagramCanvas x:Name="MainCanvas"
DockPanel.Dock="Top"
Margin="0"
MinHeight="450"
AllowDrop="True" Background="White">
</cc:DiagramCanvas>
Here is the custom canvas object and the drag drop handler
public class DiagramCanvas : Canvas
{
public DiagramCanvas()
{
this.Drop += DoDrop;
this.DragEnter += MainCanvas_DragEnter;
}
readonly MainWindow mainWin = (MainWindow)Application.Current.MainWindow;
#region works dont touch
public void DoDrop(object sender, DragEventArgs e)
{
var mainWin = (MainWindow)App.Current.MainWindow;
DragDropHandler<StateVM>.Instance.Drop(sender, e);
}
private void MainCanvas_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effects = DragDropEffects.Copy;
else
e.Effects = DragDropEffects.None;
e.Handled = true;
}
#endregion
//other code here
}
Here is the drag drop handler singleton
public sealed class DragDropHandler<T> where T : Control
{
#region singleton
private static DragDropHandler<T> instance = null;
private static readonly object padlock = new object();
DragDropHandler()
{
}
public static DragDropHandler<T> Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new DragDropHandler<T>();
}
return instance;
}
}
private set
{
instance = value;
}
}
#endregion
public static bool IsDragging { get; set; }
public static WrapPanel AllowedDragSource { get; set; }
readonly MainWindow mainWin = (MainWindow)Application.Current.MainWindow;
public static void CreateInstance(WrapPanel allowedSource)
{
if (DragDropHandler<T>.IsDragging == false)
{
instance = new DragDropHandler<T>();
DragDropHandler<T>.AllowedDragSource = allowedSource;
}
}
public void Drag(object sender, MouseEventArgs e)
{
if (sender as T == null
|| mainWin.Radio_EditStates.IsChecked == false
|| e.LeftButton != MouseButtonState.Pressed
|| IsDragging == true)
{
e.Handled = true;
return;
}
var item = (T)sender;
if (Control.ReferenceEquals(item.Parent, AllowedDragSource) == false)
{
e.Handled = true;
return;
}
IsDragging = true;
DragDrop.DoDragDrop(((StateVM)sender), new DataObject(((StateVM)sender)), DragDropEffects.Copy);
IsDragging = false;
e.Handled = true;
}
public void Drop(object sender, DragEventArgs e)
{
var mainWin = (MainWindow)App.Current.MainWindow;
if (IsDragging)
{
//TODO: Switch here to handle different shapes
var pos = e.GetPosition(mainWin.MainCanvas);
//
Canvas.SetLeft(item, pos.X.RoundDownTo10());
Canvas.SetTop(item, pos.Y.RoundDownTo10());
//update main win observalbe collections to inclue the item dropped
IsDragging = false;
e.Handled = true;
DestroyInstance();
}
}
private static void DestroyInstance()
{
DragDropHandler<T>.Instance = null;
}
}
Here is the on mouse move code for the item you are dragging
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.LeftButton == MouseButtonState.Pressed && Control.ReferenceEquals(this.Parent, mainWin.libraryContainer))
{
DragDropHandler<StateVM>.CreateInstance(mainWin.libraryContainer);
if (DragDropHandler<StateVM>.Instance != null)
{
DragDropHandler<StateVM>.Instance.Drag(this, e);
}
}
}
I have a project that uses a System.Windows.Controls.Primatives.Popup to drag a 'tooltip' like control along with a mouse.
Whenever the drag crosses a horizontal line the popup 'wraps' to the bottom of the screen - despite having sane values for the VerticalOffset. The point at which this wrapping occurs appears to be tied to the HEIGHT of the window, but not it's position.
Here's the code from the sandbox project I have created that also exhibits the same behavior:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.MainGrid.MouseDown += Grid_MouseDown;
this.MainGrid.MouseUp += Grid_MouseUp;
this.MainGrid.MouseMove += (s, e) => { if (this.Popup.IsOpen) { Popup_Drag(s, e); } };
this.Popup.MouseMove += Popup_Drag;
}
private void Popup_Drag(object sender, MouseEventArgs e)
{
Popup.HorizontalOffset = e.GetPosition(this.Popup).X;
Popup.VerticalOffset = e.GetPosition(this.Popup).Y;
this.Status_Top.Text = String.Format("Height/Top: {0}/{1} Width/Left: {2}/{3}", this.Height, this.Top, this.Width, this.Left);
this.Status.Text = String.Format("Vertical Offset: {0} Horizontal Offset: {1}", Popup.VerticalOffset, Popup.HorizontalOffset);
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
this.Popup.IsOpen = false;
}
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
this.Popup.IsOpen = true;
Popup_Drag(sender, e);
}
}
And the Window XAML:
<Window x:Class="WpfSandbox.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">
<Grid x:Name="MainGrid" Background="Purple">
<TextBlock x:Name="Status_Top"></TextBlock>
<Popup x:Name="Popup" Cursor="Hand" HorizontalAlignment="Left"
VerticalAlignment="Bottom" IsOpen="True">
<TextBlock Background="Blue" Foreground="White">
<TextBlock x:Name="Status">TEXT</TextBlock></TextBlock>
</Popup>
</Grid>
</Window>
I was able to fix this by adding Placement="RelativePoint" to the Popup attributes. Apparently this is the default in Silverlight, but not WPF.
I'm kinda confused with some problem, I'm doing a project where the user should be able to design questions with radio buttons, combo box, etc (kinda like toolbox from VS10 to design your XAML).
So far I can drag and drop an UIElement that I previously created, problem comes when the user creates a new element from my toolbox, I can't find the way to make that new UIElement to get the same events from my previosly created UIElement. Take a look at the code
<Window x:Class="WpfApplication1.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">
<Grid>
<Canvas Height="190" HorizontalAlignment="Left" Margin="158,41,0,0" Name="canvas1" VerticalAlignment="Top" Width="322" AllowDrop="True">
<Button Content="PROBANDO" Height="23" Name="button" Width="75" Canvas.Left="113" Canvas.Top="43" PreviewMouseDown="button_PreviewMouseDown" PreviewMouseMove="button_PreviewMouseMove" MouseUp="button_MouseUp" IsEnabled="True" />
<TextBlock Canvas.Left="99" Canvas.Top="147" Height="23" Name="textBlock" Text="" Width="107" />
</Canvas>
<ListBox Height="190" Name="listBox" Width="126" Margin="12,41,365,80" >
<ListBoxItem Content="Radio Button" Selected="radio_Selected" Name="radio" />
<ListBoxItem Content="Text" Selected="text_Selected" Name="text" />
<ListBoxItem Content="Combo Box" Name="combo" Selected="combo_Selected" />
</ListBox>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Point p;
private void button_MouseUp(object sender, MouseButtonEventArgs e)
{
button.ReleaseMouseCapture();
}
private void button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
button.CaptureMouse();
p = e.GetPosition(canvas1);
}
private void button_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point x = e.GetPosition(canvas1);
if (e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(button, Canvas.GetLeft(button) + (x.X - p.X));
Canvas.SetTop(button, Canvas.GetTop(button) + (x.Y - p.Y));
}
p = x;
}
private void generic_PreviewMouseDown(UIElement sender, MouseEventArgs e)
{
Point x = e.GetPosition(canvas1);
if (e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(sender, Canvas.GetLeft(sender) + (x.X - p.X));
Canvas.SetTop(sender, Canvas.GetTop(sender) + (x.Y - p.Y));
}
p = x;
}
private void radio_Selected(object sender, RoutedEventArgs e)
{
RadioButton newRadio = new RadioButton();
canvas1.Children.Add(newRadio);
newRadio.PreviewMouseDown += generic_PreviewMouseDown(newRadio,?????);
textBlock.Text = listBox.SelectedIndex.ToString();
}
private void text_Selected(object sender, RoutedEventArgs e)
{
TextBox newText = new TextBox();
canvas1.Children.Add(newText);
textBlock.Text = (String)listBox.SelectedIndex.ToString();
}
private void combo_Selected(object sender, RoutedEventArgs e)
{
Console.Write("Combo");
textBlock.Text = (String)listBox.SelectedIndex.ToString();
}
}
Thanks!
If all you want to do is handle the mouse down on the new RadioButton, change this line:
newRadio.PreviewMouseDown += generic_PreviewMouseDown(newRadio,?????);
To this:
newRadio.PreviewMouseDown += generic_PreviewMouseDown;
Edit
And then you need to change the generic_PreviewMouseDown to the following:
private void generic_PreviewMouseDown(object sender, MouseEventArgs e)
{
UIElement elem = sender as UIElement;
Point x = e.GetPosition(canvas1);
if (e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(elem, Canvas.GetLeft(elem) + (x.X - p.X));
Canvas.SetTop(elem, Canvas.GetTop(elem) + (x.Y - p.Y));
}
p = x;
}
I have a canvas in grid. On the mousemove event of canvas i am trying to translate the canvas. It works fine. However my canvas doesn't occupy the full space in the grid. What changes do i need to make in this program so that the canvas occupies the full space.
This is my xaml :-
<UserControl x:Class="SilverlightTestCanvasDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Canvas x:Name="canvas" Margin="0" Background="Red">
<TextBlock Canvas.Left="84" TextWrapping="Wrap" Text="This is some text to test whether screen is moving" Canvas.Top="99" Height="84" Width="196" FontSize="18.667" FontFamily="Cambria"/>
</Canvas>
</Grid>
</UserControl>
This is the code :-
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace SilverlightTestCanvasDemo
{
public partial class MainPage : UserControl
{
private bool _isDown = false;
private Point _lastPoint;
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
canvas.MouseLeftButtonDown += canvas_MouseLeftButtonDown;
canvas.MouseLeftButtonUp += canvas_MouseLeftButtonUp;
canvas.MouseMove += canvas_MouseMove;
}
void canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (_isDown)
{
Point point = e.GetPosition(canvas);
double deltaX = point.X - _lastPoint.X;
double deltaY = point.Y - _lastPoint.Y;
CompositeTransform transform = null;
if (!(canvas.RenderTransform is CompositeTransform))
{
transform = new CompositeTransform();
canvas.RenderTransform = transform;
}
else
{
transform = canvas.RenderTransform as CompositeTransform;
}
transform.TranslateX += deltaX;
transform.TranslateY += deltaY;
//canvas.Height += deltaY;
//canvas.Width += deltaX;
_lastPoint = e.GetPosition(canvas);
}
}
void canvas_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_isDown = false;
}
void canvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_isDown = true;
_lastPoint = e.GetPosition(canvas);
}
}
}
Thanks in advance :)
Try this:-
<Grid x:Name="LayoutRoot">
<Canvas x:Name="canvas" Margin="0" Background="AliceBlue">
<Canvas>
<TextBlock Canvas.Left="84" TextWrapping="Wrap" Text="This is some text to test whether screen is moving" Canvas.Top="99" Height="84" Width="196" FontSize="18.667" FontFamily="Cambria"/>
</Canvas>
</Canvas>
</Grid>
and tweak the mouse move code behind to this:-
void canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (_isDown)
{
Point point = e.GetPosition(canvas);
double deltaX = point.X - _lastPoint.X;
double deltaY = point.Y - _lastPoint.Y;
CompositeTransform transform = null;
if (!(canvas.Children[0].RenderTransform is CompositeTransform))
{
transform = new CompositeTransform();
canvas.Children[0].RenderTransform = transform;
}
else
{
transform = canvas.Children[0].RenderTransform as CompositeTransform;
}
transform.TranslateX += deltaX;
transform.TranslateY += deltaY;
_lastPoint = e.GetPosition(canvas);
}
}
What's happening here is a second inner Canvas is being used as a caddy to hold the set of actual children. Now you need only transform this inner canvas to move all the content about.
Is there anyone who experienced with the scrollviewer component in WPF? I have a basic selection zoom, and the problem is that it does not scroll to the right place.
Output, trying to zoom the flower:
Actually, the RectangleZoom (see bellow) method scales the picture, but it does not focus it on the specified rectangle, but always in the same position... I believe there is a way to scroll to that position, but till now, any success....
Here is my code:
XAML:
<Window x:Class="WpfApplication3.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">
<ScrollViewer x:Name="scrollViewer"
HorizontalScrollBarVisibility="Auto">
<Canvas Height="200" Name="mainCanvas" Width="400"
MouseLeftButtonDown="mainCanvas_MouseLeftButtonDown"
MouseLeftButtonUp="mainCanvas_MouseLeftButtonUp"
MouseMove="mainCanvas_MouseMove">
<Canvas.Background>
<ImageBrush ImageSource="/WpfApplication3;component/Images/natural-doodle.jpg"/>
</Canvas.Background>
<Canvas.LayoutTransform>
<TransformGroup>
<ScaleTransform x:Name="scaleTransform"/>
</TransformGroup>
</Canvas.LayoutTransform>
</Canvas>
</ScrollViewer>
</Window>
Code behind:
public partial class MainWindow : Window
{
private Point startPoint;
private Point endPoint;
private Shape rubberBand;
public MainWindow()
{
InitializeComponent();
}
private void mainCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (!mainCanvas.IsMouseCaptured)
{
startPoint = e.GetPosition(mainCanvas);
Mouse.Capture(mainCanvas);
}
}
private void mainCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (mainCanvas.IsMouseCaptured)
{
if (rubberBand != null)
{
this.RectangleZoom(
Canvas.GetLeft(rubberBand),
Canvas.GetTop(rubberBand),
rubberBand.Width,
rubberBand.Height);
mainCanvas.Children.Remove(rubberBand);
rubberBand = null;
mainCanvas.ReleaseMouseCapture();
}
}
}
private void mainCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (mainCanvas.IsMouseCaptured)
{
endPoint = e.GetPosition(mainCanvas);
if (rubberBand == null)
{
rubberBand = new Rectangle();
rubberBand.Stroke = Brushes.Red;
rubberBand.StrokeDashArray = new DoubleCollection(new double[] { 4, 2 });
mainCanvas.Children.Add(rubberBand);
}
rubberBand.Width = Math.Abs(startPoint.X - endPoint.X);
rubberBand.Height = Math.Abs(startPoint.Y - endPoint.Y);
double left = Math.Min(startPoint.X, endPoint.X);
double top = Math.Min(startPoint.Y, endPoint.Y);
Canvas.SetLeft(rubberBand, left);
Canvas.SetTop(rubberBand, top);
}
}
private void RectangleZoom(double x, double y, double width, double height)
{
double rWidth = scrollViewer.ViewportWidth / width;
double rHeight = scrollViewer.ViewportHeight / height;
double rZoom = 1.0;
if (rWidth < rHeight)
rZoom = rWidth;
else
rZoom = rHeight;
scaleTransform.ScaleX = rZoom;
scaleTransform.ScaleY = rZoom;
}
}
You got it all but three lines:
Add these to the bottom of your RetangleZoom method:
Point newXY = scaleTransform.Transform(new Point(x, y));
scrollViewer.ScrollToHorizontalOffset(newXY.X);
scrollViewer.ScrollToVerticalOffset(newXY.Y);