Moving Image in ScrollViewer (UWP) - c#

I've got a Image in Scrollviewer...
<ScrollViewer x:Name="Scrollster" ZoomMode="Enabled" MinZoomFactor="1" MaxZoomFactor="4"
HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" ManipulationMode="All">
<Image x:Name="Img" Source="{x:Bind ImgSource}" Stretch="UniformToFill" PointerPressed="Img_PointerPressed"/>
</ScrollViewer>
I want to move Image when I drag image with Mouse Pointer!
I tried:
private void Img_PointerPressed(object sender,PointerRoutedEventArgs e)
{
var p = e.Pointer;
}
but I can't get pointer position to change scrollviewer postion.
What's wrong with my code? Am I doing it right?

The ManipulationMode should be set on the Img control instead. Also, you probably want to specify the exact modes you want rather than All to prevent unnecessary gesture handling.
<Image x:Name="Img" Source="{x:Bind ImgSource}" Width="150" Height="150" Stretch="UniformToFill"
ManipulationMode="TranslateX, TranslateY"
ManipulationStarted="Img_ManipulationStarted"
ManipulationDelta="Img_ManipulationDelta"
ManipulationCompleted="Img_ManipulationCompleted">
<Image.RenderTransform>
<CompositeTransform x:Name="Transform" />
</Image.RenderTransform>
</Image>
From your description above, I think turning on both TranslateX and TranslateY should be sufficient. Then you will need to handle manipulation events like ManipulationStarted, ManipulationDelta and ManipulationCompleted.
Most of your logic should be done in ManipulationDelta event which will be fired multiple times during the progression of the panning. It's where you get the X and Y positions and set them accordingly.
Here is a simple sample for this.
void Img_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
// dim the image while panning
this.Img.Opacity = 0.4;
}
void Img_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
this.Transform.TranslateX += e.Delta.Translation.X;
this.Transform.TranslateY += e.Delta.Translation.Y;
}
void Img_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
// reset the Opacity
this.Img.Opacity = 1;
}

Related

WPF Canvas Panning and Zoom

I've created an application that can read an XML file and display the rail network specified within a WPF Canvas.
I've been struggling for a while (months) to get the following functionality working and looking for any clue on how to proceed:
Zoom using mousewheel (zooming in makes the icons and tracks bigger whilst zooming out can let me see all the network).
Panning - Using the middle mouse button to drag the view screen.
I ended up having to disable the mouse wheel as it just moved the scrollviewer. In order for me to scroll currently, I have to use the scrollbar arrows.
Usually I would upload code samples but I've also uploaded everything to GitHub with everything needed in case you need to dive into the code or compile.
https://github.com/Legolash2o/NMViewer
XAML
<ScrollViewer x:Name="svCanvas" Grid.Row="2" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" MouseMove="CCanvas_OnMouseMove" PreviewMouseWheel="SvCanvas_OnPreviewMouseWheel" MouseWheel="SvCanvas_OnPreviewMouseWheel" MouseDown="SvCanvas_OnMouseDown">
<Canvas x:Name="cMain" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="36000" Height="58000" >
<Canvas.RenderTransform>
<ScaleTransform x:Name="st"/>
</Canvas.RenderTransform>
</Canvas>
</ScrollViewer>
C#
private void SvCanvas_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
}
private void SvCanvas_OnMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.MiddleButton == MouseButtonState.Pressed)
{
st.ScaleX = 1;
st.ScaleY = 1;
}
}
private void CCanvas_OnMouseMove(object sender, MouseEventArgs e)
{
if (drawing)
return;
lblBar.Content =
$"H[{svCanvas.HorizontalOffset}, V{svCanvas.VerticalOffset}] Mouse: {Mouse.GetPosition(cMain)}";
}

How To Let A Grid Capture The Mouse, But Still Allow It's Children To Handle Click Events

Sorry in advance if the title is confusing. Here's the situation. I have a grid called grdFilters. This grid has a series of CheckBoxes within it (one per row). Normally this grid is hidden. But I wanted it to show up when prompted (on button click) and leave when the user clicks somewhere other than the grid. To handle outside control mouse clicks I tried first capturing the mouse as such:
AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(HandleClickOutsideOfControl));
private void HandleClickOutsideOfControl(object sender, MouseButtonEventArgs e)
{
if (this.filters) //Check if the Filters grid is visible
{
ShowHideMenu("sbHideFilters", grdFilters); //Method that hides the grid
Mouse.Capture(null); //Release the mouse
}
}
private void btnFilters_Click(object sender, RoutedEventArgs e)
{
if (!this.filters) //Check if the filters grid is shown
{
ShowHideMenu("sbShowFilters", grdFilters); //Method that reveals the grid
Mouse.Capture(grdFilters); //Capture the mouse
}
}
The problem is that while the Filters grid has captured the mouse, none of the grids children (the Check Boxes) can be clicked on. I would really like to find a way to detect when the mouse is clicked outside of the grid while still allowing the children of the grid to accept mouse down events. Any help would be greatly appreciated, thanks in advance.
As per request here is some of my Xaml:
<Grid>
<Label x:Name="label" Content="Events" HorizontalAlignment="Center" VerticalAlignment="Top"/>
<ScrollViewer HorizontalAlignment="Left" Height="619" Margin="0,26,0,0" VerticalAlignment="Top" Width="450" VerticalScrollBarVisibility="Hidden">
<Grid x:Name="Schedule" HorizontalAlignment="Left" Height="Auto" VerticalAlignment="Top" Width="450" Margin="10,0,0,0"/>
</ScrollViewer>
<Grid x:Name="grdFilters" HorizontalAlignment="Left" Height="619" Margin="490,26,-176,0" VerticalAlignment="Top" Width="135" Background="{StaticResource TransparentBackground}" Panel.ZIndex="95">
<CheckBox x:Name="chckAll" Content="All" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Checked="chckAll_Checked" Unchecked="chckAll_Unchecked"/>
<Grid x:Name="grdFilters" HorizontalAlignment="Left" Height="588" Margin="0,31,0,0" VerticalAlignment="Top" Width="136"/>
</Grid>
<Button x:Name="btnFilters" Content="" Margin="436,223,-18,0" VerticalAlignment="Top" Background="Cyan" Opacity="0.15" Style="{StaticResource MyTabStyle}" Height="80" Click="btnFilters_Click"/>
</Grid>
The only thing I left out were the Resource Dictionaries and the page definition itself.
I think the Mouse.Capture and PreviewMouseDownOutsideCapturedElementEvent and are too specific for what you want.
I would rather use a hitResultsList, which can be used in a lot of different scenarios:
I slightly modified eh AddHandler
AddHandler(Mouse.PreviewMouseDownEvent, new MouseButtonEventHandler(HandleMouseDown));
And I added the VisualTreeHelper.HitTest logic
//List to store all the elements under the cursor
private List<DependencyObject> hitResultsList = new List<DependencyObject>();
private void HandleMouseDown(object sender, MouseButtonEventArgs e)
{
Point pt = e.GetPosition((UIElement)sender);
hitResultsList.Clear();
//Retrieving all the elements under the cursor
VisualTreeHelper.HitTest(this, null,
new HitTestResultCallback(MyHitTestResult),
new PointHitTestParameters(pt));
//Testing if the grdFilters is under the cursor
if (!hitResultsList.Contains(this.grdFilters) && grdFilters.Visibility == System.Windows.Visibility.Visible)
{
grdFilters.Visibility = System.Windows.Visibility.Hidden;
}
}
//Necessary callback function
private HitTestResultBehavior MyHitTestResult(HitTestResult result)
{
hitResultsList.Add(result.VisualHit);
return HitTestResultBehavior.Continue;
}
that way you can also remove the Mouse.Capture call from the btnFilters_Click:
private void btnFilters_Click(object sender, RoutedEventArgs e)
{
if (grdFilters.Visibility != System.Windows.Visibility.Visible)
grdFilters.Visibility = System.Windows.Visibility.Visible; }
}

Draggable StackPanel Windows Phone 8.1

I'm developing a Windows Phone 8.1 app with a MapControl as the main focal point of my app. I basically want to integrate a similar experience design wise as the Nokia Here Maps App.
The bottom black Frame can be pulled upwards to reveal its content.
How am I able to do this?
EDIT
I now have:
ExtraInfo.RenderTransform = new TranslateTransform();
ExtraInfo.ManipulationDelta += OnManipulationDelta;
ExtraInfo.ManipulationMode = Windows.UI.Xaml.Input.ManipulationModes.TranslateY;
in my constructor
The eventhandler
private void OnManipulationDelta(object sender, Windows.UI.Xaml.Input.ManipulationDeltaRoutedEventArgs e)
{
try
{
Storyboard myStoryboard = (Storyboard)this.Resources["TestStoryboard"];
TranslateTransform myTranslate = new TranslateTransform();
myTranslate.Y = e.Delta.Translation.Y;
ExtraInfo.RenderTransform = myTranslate;
Storyboard.SetTarget(myStoryboard.Children[0] as DoubleAnimation, ExtraInfo);
myStoryboard.Begin();
}
catch (Exception)
{
Debug.WriteLine("Animation called");
}
}
My XAML
<Grid>
<StackPanel>
<Maps:MapControl Height="{Binding ActualHeight, ElementName=pageRoot}" x:Name="Map" LandmarksVisible="False" ZoomLevel="{Binding zoomlevel, Mode=TwoWay, FallbackValue=8}" MapServiceToken="#######" TrafficFlowVisible="True">
<Image x:Name="NewCheckImage" Visibility="Collapsed" Maps:MapControl.Location="{Binding Center, ElementName=Map}" Maps:MapControl.NormalizedAnchorPoint=".5,.5"></Image>
</Maps:MapControl>
<StackPanel x:Name="ExtraInfo" Height="{Binding ActualHeight, ElementName=pageRoot}" Background="Black" Margin="0,-250,0,0" Canvas.ZIndex="1">
<StackPanel.RenderTransform>
<TranslateTransform X="0" Y="0">
</TranslateTransform>
</StackPanel.RenderTransform>
</StackPanel>
</StackPanel>
</Grid>
The storyboard
<Page.Resources>
<Storyboard x:Key="TestStoryboard">
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.Y)"
To="0">
</DoubleAnimation>
</Storyboard>
</Page.Resources>
But the panel does some jumpy unpredictable moves.
Set RenderTransform = new TranslateTransform() for your StackPanel, handle Page ManipulationDelta event and there change your (StackPanel.RenderTransform as TranslateTransform).Y value. Use Storyboard (animation on RenderTransform) to achieve effect of pulling up/down on touch release.
You should do something like this: (pseudocode)
void OnStackPanelLoaded(..)
{
StackPanel.VerticalAlingment = VerticalAlingment.Bottom;
StackPanel.RenderTransform = new TranslateTransform(0, StackPanel.ActualHeight);
// translate stackpanel out of page, be sure stackpanel has bottom alingment of grid
}
void OnManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs args)
{
var stackPanelTransform = MyStackPanel.RenderTransform as TranslateTransform;
stackPanelTransform.Y += args.Delta.Translation.Y;
}
You should also register to ManipulationCompleted event and there run close/open animation.
void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs args)
{
// you can also add additional logic here to reverse open/close logic
// for example: if user touch translation delta is too small then instead of opening panel - close it like in Here
if (IsPanelOpened())
Resources["ClosePanelStoryboard"].BeginStoryboard();
else
Resources["OpenPanelStoryboard"].BeginStoryboard();
}
bool IsPanelOpened()
{
var translateTransform = myStackPanel.RenderTransform as TranslateTransform;
return translateTransform.Y > double.Epsilon;
}
Check DoubleAnimation.EasingFunction - to achieve same animation effect like in Here Drive (animated open/close).
Implementing good panel takes time. Initially it should have Opacity = 0, IsHitTest = false (because it can blink on page start - before RenderTransform is set) - you should also register to SizeChanged event in StackPanel to ensure that TranslateTransform is set correctly (sometimes you can get StackPanel.ActualHeight value of 0 - most likely in release build because they're faster).

What event fires when user lifts finger from ScrollViewer on touch capable screens

I'm finding that when I tap the ScrollViewer, the PointerPressed and PointerExited events fires as expected. But, if I scroll in any direction after touching the screen and lift my finger, no event fires except for PointerCaptureLost which prematurely fires as soon as I scroll.
When I capture the pointer ID and poll the status of the PointerPoint with a timer, the IsInContact flag remains true, even after I lift my finger after scrolling. It works as expected when I simply tap the screen.
ManipulationCompleted has the same effect as above, and I cannot use the ViewChanged event since this fires before I lift my finger.
Is this a bug or am I missing something here? Is there another way I can detect when a user has lifted their finger off the screen? This is driving me bananas.
Sample code below. You'll need to use the simulator in touch-mode or have a touch capable screen to test:
Code:
using System;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace App1
{
public sealed partial class MainPage : Page
{
private readonly DispatcherTimer pointerTimer = new DispatcherTimer();
private uint? CurrentPointerID; //container for the current pointer id when user makes contact with the screeen
public MainPage()
{
this.InitializeComponent();
scrollviewer.PointerPressed += scrollviewer_PointerPressed;
scrollviewer.PointerMoved += scrollviewer_PointerMoved;
scrollviewer.PointerExited += scrollviewer_PointerExited;
scrollviewer.PointerReleased += scrollviewer_PointerReleased;
scrollviewer.PointerCaptureLost += scrollviewer_PointerCaptureLost;
scrollviewer.PointerCanceled += scrollviewer_PointerCanceled;
pointerTimer.Tick += pointerTimer_Tick;
pointerTimer.Interval = TimeSpan.FromMilliseconds(300);
pointerTimer.Start();
}
#region ScrollViewer Events
void scrollviewer_PointerMoved(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Moved";
}
void scrollviewer_PointerExited(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Exited";
}
void scrollviewer_PointerPressed(object sender, PointerRoutedEventArgs e)
{
CurrentPointerID = e.Pointer.PointerId;
EventCalledTextBlock.Text = "Pointer Pressed";
}
void scrollviewer_PointerCanceled(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Canceled";
}
void scrollviewer_PointerCaptureLost(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Capture Lost";
}
void scrollviewer_PointerReleased(object sender, PointerRoutedEventArgs e)
{
EventCalledTextBlock.Text = "Pointer Released";
}
#endregion
void pointerTimer_Tick(object sender, object e)
{
if (!CurrentPointerID.HasValue)
{
PollingTextBlock.Text = string.Empty;
return;
}
try
{
var pointerPoint = PointerPoint.GetCurrentPoint(CurrentPointerID.Value);
PollingTextBlock.Text = pointerPoint.IsInContact ? "Is In Contact" : "Not in Contact";
}
catch (Exception ex)
{
//This exception is raised when the user lifts finger without dragging.
//assume finger is not in contact with screen
PollingTextBlock.Text = "Not in Contact";
}
}
}
}
XAML:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Name="grid">
<Grid.RowDefinitions>
<RowDefinition Height="113*"/>
<RowDefinition Height="655*"/>
</Grid.RowDefinitions>
<ScrollViewer x:Name="scrollviewer" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Visible" Grid.Row="1" >
<Rectangle Fill="#FF3783CF" Height="100" Stroke="#FF33D851" Width="{Binding ElementName=grid, Path=ActualWidth}" Margin="100" StrokeThickness="4" />
</ScrollViewer>
<StackPanel Orientation="Vertical" Margin="45,25,0,0">
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Event Called:" VerticalAlignment="Top" FontSize="24" Margin="0,0,20,0"/>
<TextBlock x:Name="EventCalledTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="24"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Polling Value:" VerticalAlignment="Top" FontSize="24" Margin="0,0,20,0"/>
<TextBlock x:Name="PollingTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="24"/>
</StackPanel>
</StackPanel>
</Grid>
</Page>
I stumbled upon this question since I was struggling with a similar problem. I have a ScrollViewer which has several images in it and I wanted to know what images are shown at the moment the ScrollViewer stops moving...
In the end I did used the ScrollViewer.ViewChanged event. This event keeps triggering untill it has finished with scrolling.
I actually am only interested in the last of these events, but since there is no event that triggers only on that particular moment I need to respond to this one and check for myself if this is the appropriate moment to take actions.
I hope this helps.
ScrollViewer.ViewChanged event: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.scrollviewer.viewchanged?f=255&MSPPError=-2147217396
I think you need to use the PointerReleased event.
Refer to the following link: https://msdn.microsoft.com/library/windows/apps/br208279

WPF: Opacity and the MouseEnter Event

As part of a diagram, I am drawing a few overlapping Shapes, each with Opacity=0.5, like here:
<Grid>
<Rectangle Fill="Blue" Opacity="0.5" MouseEnter="Rectangle_MouseEnter" />
<Rectangle Fill="Red" Opacity="0.5" />
</Grid>
private void Rectangle_MouseEnter(object sender, MouseEventArgs e)
{
MessageBox.Show("Entered");
}
When the user enters the shape with the mouse, some additional information should be displayed, but the event handler never gets called.
Is there a way to get MouseEnter events for all Shapes, instead of just the topmost one?
With your layout only the topmost rectangle will raise MouseEnter event. It fully overlaps the first rectangle.
Try this code for eventHandler:
private void Rectangle_MouseEnter(object sender, MouseEventArgs e)
{
if (sender != grid.Children[0])
{
var rect = (grid.Children[0] as Rectangle);
if (rect != null) rect.RaiseEvent(e);
}
else
{
MessageBox.Show("Entered.");
}
}
For this works you need to subscribe both rectangles to Rectangle_MouseEnter.

Categories