Viewport3D Mouse Event doesn't fire when hitting background - c#

I set up a Viewport3D with a MouseEventHandler
[...]
Main3DWindow.MouseUp += new MouseButtonEventHandler(mainViewport_MouseUp);
[...]
void mainViewport_MouseUp (object sender, MouseButtonEventArgs e) {
Point location = e.GetPosition(Main3DWindow);
ModelVisual3D result = GetHitTestResult(location);
if (result == null) {
_CurrentData.Unselect();
return;
}
_CurrentData.SelectItemFromObjectList(result);
}
And it works pretty fine when an object is clicked.
My expectation was: If no object is clicked (because the user clicked at the background) the result is null. But in fact the mainViewport_MouseUp-method is not even called.
My question: how can i detect clicks on the background of the Viewport3D?

It is as you wrote, it wont be fired.
I solved that by defining events on border and put viewport into border. Sample is from XAML:
<Border
MouseWheel="mainViewport_MouseWheel"
MouseMove="mainViewport_MouseMove"
MouseLeftButtonDown="mainViewport_MouseLeftButtonDown"
Background="Black">
<Viewport3D
Name="mainViewport"
ClipToBounds="True"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="3"
Margin="0,0,0,0">
.....
</Viewport3D>
</Border>
And in the code:
private void mainViewport_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point location = e.GetPosition(mainViewport);
try
{
ModelVisual3D result = (ModelVisual3D)GetHitTestResult(location);
//some code.......
}
catch
{
//some code .......
}
}

Related

WPF: Button with custom template is not clickable as whole [duplicate]

I am trying to practice c# by reproduce an App that is in the Apple AppStore.
In the app, there is a rectangle with the text: "Touch me". When you touch it, the rectangle repositions itself.
After you do this a few times, the text changes to "Do not Touch me". In that case you have to Touch outside of the rectangle.
It all went well, up to the point where you have to touch outside the rectangle.
Here is my event handler:
private void Canvas_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
if (click == 0)
{
if (rectangle1.IsMouseOver || textBlock1.IsMouseOver)
{
// reposition and stuff
if (clicks == 10)
{
// Change the value of the variable click to 1
click = 1;
textBlock1.Text = "Do Not Click me";
Canvas.SetLeft(textBlock1, 200);
}
}
}
else
{
if (rectangle1.IsMouseOver || textBlock1.IsMouseOver)
{
// Game Over
this.Close();
} else
{
// reposition and stuff
click = 0;
textBlock1.Text = "Click me";
Canvas.SetLeft(textBlock1, 225);
}
}
}
The program works perfectly up to the point where you have to click outside the rectangle.
The program closes when you click on the rectangle but when you click outside it, nothing happens.
Is there any event-handler that can do the task i want?
Here is my xaml
<Window x:Class="ClickMe.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="510" Width="525" ResizeMode="NoResize">
<Canvas Name="canvas" MouseLeftButtonDown="Canvas_MouseLeftButtonDown_1">
<Rectangle Fill="#FFF4F4F5" Name="rectangle1" HorizontalAlignment="Left" Height="38" Stroke="Black" VerticalAlignment="Top" Width="509" Canvas.Left="0" Canvas.Top="63"/>
<Label Name="label1" Content="0" Canvas.Left="57" Canvas.Top="446"/>
<Label Content="Klicks:" Canvas.Left="10" Canvas.Top="446"/>
<TextBlock Name="textBlock1" Canvas.Left="225" TextWrapping="Wrap" Text="Click Me" Canvas.Top="74" Margin="10,0,0,0"/>
</Canvas>
Canvas is a UIElement. This allows the use of the PointerPressed event.
private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
{
Windows.UI.Xaml.Input.Pointer ptr = e.Pointer;
if (ptr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
{
Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(Target);
if (ptrPt.Properties.IsLeftButtonPressed)
{
//do yo thang
}
}
}
You really just need to set the Background of the Canvas, as it only gets mouse input where it has "rendered content". The background could even be transparent:
<Canvas Name="canvas" Background="Transparent"
MouseLeftButtonDown="Canvas_MouseLeftButtonDown_1">
...
</Canvas>
use this instead of Canvas_MouseLeftButtonDown_1 event:
protected override OnMouseDown(MouseButtonEventArgs e)
{
if(e.Changed == MouseButton.Left)
{
// Your logic on mouse down will go here
}
base.OnMouseDown(e);
}
with this you can click anywhere on the canvas and get the event to fire. I hope this helps..

Let image ManipulationMode capture pointer

In my app, a user can select an Image and drag it onto a Grid, to play with it. I do this by handling the PointerEntered event of the Grid. Here I detect if the user had an image selected and if the user is holding the mouse button.
Now I want to place the Image on the grid, and pass on the (still pressed down) pointer to my Image, so the Image uses its own ManipulationStarted, ManipulationDelta and ManipulationCompleted events. This should let the user drag the image in one smooth movement from the list of images to the Grid, instead of having to release and click on the element.
I have tried releasing the pointer from the sender in PointerEntered, and capturing it using CapturePointer, but that doesn't seem to work, even though the CapturePointer returns true.
Here is the code I use for the PointerEntered event:
private void DrawingArea_OnPointerEntered(object sender, PointerRoutedEventArgs e)
{
// If we enter the grid while dragging and we have an image that was dragged
if (e.Pointer.IsInContact && CurrentDraggedImage != null)
{
DrawingArea.Children.Add(CurrentDraggedImage);
// Move it to the location we're currently at
var transform = (CurrentDraggedImage.RenderTransform as CompositeTransform);
transform.TranslateX += e.GetCurrentPoint(DrawingArea).RawPosition.X - DrawingArea.ActualWidth / 2;
transform.TranslateY += e.GetCurrentPoint(DrawingArea).RawPosition.Y - DrawingArea.ActualHeight/2;
// This works (I think)
(sender as UIElement).ReleasePointerCaptures();
// This doesn't work (or it isn't what I need), but returns true
CurrentDraggedImage.CapturePointer(e.Pointer);
// Get ready for a new image
CurrentDraggedImage = null;
}
}
My manipulation code is in this answer:
https://stackoverflow.com/a/32230733/1009013
Why don't you just use drag-n-drop? Create a grid containing your toolbar (e.g. a list of images to drag) and a target grid that responds to dragdrop commands:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox Background="AliceBlue" MouseMove="OnMouseMove">
<ListBox.Resources>
<Style TargetType="{x:Type Image}">
<Setter Property="Width" Value="64" />
<Setter Property="Height" Value="64" />
</Style>
</ListBox.Resources>
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_pawn_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_rook_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_knight_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_bishop_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_queen_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_king_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_pawn_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_rook_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_knight_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_bishop_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_queen_T.png" />
<Image Source="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_king_T.png" />
</ListBox>
<GridSplitter Grid.Column="1" Width="5" Background="LightGray" />
<Grid x:Name="targetGrid" Grid.Column="2" AllowDrop="True" DragEnter="OnDragEnter" DragOver="OnDragMove" DragLeave="OnDragLeave" Drop="OnDrop" Background="Transparent"/>
</Grid>
Your listbox needs a MouseMove handler to detect when an image is being dragged and your command handlers simply respond to the various events as required, cloning the require image and dragging them across the face of the grid accordingly:
public partial class MainWindow : Window
{
private Image DragImage = null;
public MainWindow()
{
InitializeComponent();
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
// make sure we have an image
var image = e.OriginalSource as Image;
if (image == null)
return;
// make sure we've started dragging
if (e.LeftButton != MouseButtonState.Pressed)
return;
DragDrop.DoDragDrop(image, image, DragDropEffects.Copy);
}
private void OnDragEnter(object sender, DragEventArgs e)
{
// make sure we have an image
if (!e.Data.GetDataPresent(typeof(Image)))
{
e.Effects = DragDropEffects.None;
return;
}
// clone the image
var image = e.Data.GetData(typeof(Image)) as Image;
e.Effects = DragDropEffects.Copy;
this.DragImage = new Image { Source = image.Source, Width=64, Height=64 };
var position = e.GetPosition(this.targetGrid);
this.DragImage.SetValue(Grid.MarginProperty, new Thickness(position.X-32, position.Y-32, 0, 0));
this.DragImage.SetValue(Grid.HorizontalAlignmentProperty, HorizontalAlignment.Left);
this.DragImage.SetValue(Grid.VerticalAlignmentProperty, VerticalAlignment.Top);
this.DragImage.IsHitTestVisible = false; // so we don't try and drop it on itself
// add it to the target grid
targetGrid.Children.Add(this.DragImage);
}
private void OnDragMove(object sender, DragEventArgs e)
{
var position = e.GetPosition(this.targetGrid);
this.DragImage.SetValue(Grid.MarginProperty, new Thickness(position.X - 32, position.Y - 32, 0, 0));
}
private void OnDragLeave(object sender, DragEventArgs e)
{
targetGrid.Children.Remove(this.DragImage);
this.DragImage = null;
}
private void OnDrop(object sender, DragEventArgs e)
{
this.DragImage.IsHitTestVisible = true;
this.DragImage = null;
}
}
Result:
I've done things the horrible and ugly WPF way here instead of clean and elegant MVVM, but you get the idea. I also don't get why you want to drag things around a Grid instead of a Canvas?

How to Get Tap Event from User Control in Page

Hopefully the question makes sense. What I would like to do is place an Ellipse (or styled button to look like an Ellipse with an icon inside in a user control that is dynamically populated in my code behind, and then be able to determine when the Ellipse was tapped on the user control and perform a separate action than when the user control is tapped. The sample I'm using actually comes from a Nokia Imaging SDK sample with a few tweaks.
PhotoThumbnail.xaml //The UserControl
<Ellipse Grid.Row="0" Grid.Column="1" Stroke="LightGray" StrokeThickness="3"
VerticalAlignment="Top" HorizontalAlignment="Right" Width="50" Height="50" Margin="7"/>
PhotoThumbnail.xaml.cs
public event PropertyChangedEventHandler PropertyChanged;
public PhotoThumbnail()
{
InitializeComponent();
DataContext = this;
}
Page.xaml.cs
//Creae PhotoThumbnail
PhotoThumbnail photoThumbnail = new PhotoThumbnail()
{
..
};
photoThumbnail.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
{
// do something
};
panel.Children.Add(photoThumbnail);
}
}
}
}
The photoThumbnail.Tap event above performs an action, but how can I determine if the user tapped the Ellipse on the PhotoThumbnail UserControl as opposed to the control itself?
I just added the following in Page.xaml.cs and named the Ellipse in the User Control x:Name="EditableEllipse"
photoThumbnail.EditableEllipse.Tap += (object sender, System.Windows.Input.GestureEventArgs e) =>
{
if (sender != null)
{
.. do something ..
}
};

How to detect if the scroll viewer reaches bottom in winrt

I'm wondering what's the best approach to detect if a ScrollViewer reaches the bottom, right etc.
I think I can achieve that by using both PointerWheelChanged for mouse and ManipulationDelta for touch. In these event handlers, I can record the HorizontalOffset to find out when will the scroller reach the end. But I think there could be a better way to do it.
I've found this article. But the compression visual states seem not working in winrt. The CurrentStateChanging event method is not getting called.
I also checked another article. But it just works for scroll bar, not a generic approach.
Anyone knows what's the best way to solve this problem?
XAML:
<ScrollViewer
x:Name="sv"
ViewChanged="OnScrollViewerViewChanged">
<Rectangle
x:Name="rect"
Width="2000"
Height="2000"
Fill="Yellow"
Margin="10" />
</ScrollViewer>
Code behind:
private void OnScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var verticalOffset = sv.VerticalOffset;
var maxVerticalOffset = sv.ScrollableHeight; //sv.ExtentHeight - sv.ViewportHeight;
if (maxVerticalOffset < 0 ||
verticalOffset == maxVerticalOffset)
{
// Scrolled to bottom
rect.Fill = new SolidColorBrush(Colors.Red);
}
else
{
// Not scrolled to bottom
rect.Fill = new SolidColorBrush(Colors.Yellow);
}
}
For UWP I got it like this
<ScrollViewer Name="scroll" ViewChanged="scroll_ViewChanged">
<ListView />
</ScrollViewer>
private void scroll_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
var scrollViewer = (ScrollViewer)sender;
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
btnNewUpdates.Visibility = Visibility.Visible;
}
private void btnNewUpdates_Click(object sender, RoutedEventArgs e)
{
itemGridView.ScrollIntoView(itemGridView.Items[0]);
btnNewUpdates.Visibility = Visibility.Collapsed;
}

WPF layer event separation

I have the highest layer called "canvas" which is used to display picture. Then, I'm trying to use event menuCanvas_touchDown to lowest layer called "menuCanvas" which show my workspace menu. However, when I touch the picture, it go to menuCanvas_touchDown. It should be found at the menuCanvas layer.
<Canvas x:Name="menuCanvas"
TouchDown="menuCanvas_TouchDown" TouchUp="menuCanvas_TouchUp"
TouchMove="menuCanvas_TouchMove" TouchLeave="menuCanvas_TouchLeave"
TouchEnter="menuCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Transparent"
IsManipulationEnabled="True">
<Canvas x:Name="drawCanvas"
TouchDown="drawCanvas_TouchDown" TouchUp="drawCanvas_TouchUp"
TouchMove="drawCanvas_TouchMove" TouchLeave="drawCanvas_TouchLeave"
TouchEnter="drawCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Transparent"
IsManipulationEnabled="True">
<Canvas x:Name="canvas"></Canvas>
</Canvas>
</Canvas>
I want to touch picture and nothing happen to menuCanvas_touchDown event.
How do I solve this problem? I'm trying to use e.handle, but it break the manipulation of the picture.
Thanks
Edit:
There are drawCanvas_TouchDown and drawCanvas_TouchUp code.
private void drawCanvas_TouchDown(object sender, TouchEventArgs e)
{
if (state == (int)STATE.Pen)
{
if (_activeStrokes.TryGetValue(e.TouchDevice.Id, out stroke))
{
FinishStroke(stroke);
return;
}
// Create new stroke, add point and assign a color to it.
Stroke newStroke = new Stroke();
newStroke.Color = _touchColor.GetColor();
newStroke.Id = e.TouchDevice.Id;
// Add new stroke to the collection of strokes in drawing.
_activeStrokes[newStroke.Id] = newStroke;
}
}private void drawCanvas_TouchUp(object sender, TouchEventArgs e)
{
// Find the stroke in the collection of the strokes in drawing.
if (state == (int)STATE.Pen)
{
if (_activeStrokes.TryGetValue(e.TouchDevice.Id, out stroke))
{
FinishStroke(stroke);
}
}
}
Have you try to use e.OriginalSource? You can check source of event.
if(e.OriginalSource == menuCanvas)
{
//Your code
}

Categories

Resources