private void SubscribeToStateChanging(bool subscribe = true) { if (subscribe) { this.ScrollViewer.OnScrollStateChanged = (Action <bool, bool>)((isScrolling, isManipulating) => { this.group_CurrentStateChanging(isScrolling); this._preventPullUntilNextManipulationStateChange = false; if (isManipulating && this.ScrollViewer.VerticalOffset == 0.0) { this.LockBoundsForPull(); } else { this.UnlockBounds(); } if (isScrolling) { return; } foreach (UIElement uiElement in VisualTreeHelper.FindElementsInHostCoordinates(new Point(FramePageUtils.Frame.ActualWidth / 2.0, FramePageUtils.Frame.ActualHeight / 2.0), Application.Current.RootVisual).Where <UIElement>((Func <UIElement, bool>)(e => e is INotifiableWhenOnScreenCenter))) { (uiElement as INotifiableWhenOnScreenCenter).NotifyInTheCenterOfScreen(); } }); } else { this.ScrollViewer.OnScrollStateChanged = (Action <bool, bool>)null; } }
private async Task ProcessPointer(PointerRoutedEventArgs e) { PointerPoint point = e.GetCurrentPoint(null); IEnumerable <UIElement> elements = VisualTreeHelper.FindElementsInHostCoordinates(point.Position, this.MainGrid); if (elements.Count() > 0) { // *** // *** The top UI Element will be the pixel // *** if (elements.FirstOrDefault() is Border border) { (uint row, uint column) = await this.GetPixelCoordinates(border); if (this.PreviousRow != row || this.PreviousColumn != column || this.PreviousKeyModifiers != e.KeyModifiers) { this.OnPixelChanged(new PixelSelectedEventArgs(row, column, e.KeyModifiers)); this.PreviousRow = row; this.PreviousColumn = column; this.PreviousKeyModifiers = e.KeyModifiers; } } } }
internal DragFillContextMenuItem GetTappedDragFillContextMenu(Point point) { if (IsContextMenuOpened) { Rect rect = new Rect(_dragFillPopupManager.Location.X, _dragFillPopupManager.Location.Y, _dragFillPopupManager.Size.Width, _dragFillPopupManager.Size.Height); if (!rect.Contains(point)) { return(null); } UIElement content = null; content = Windows.UI.Xaml.Window.Current.Content; if (content == null) { return(null); } List <UIElement> list = Enumerable.ToList <UIElement>(VisualTreeHelper.FindElementsInHostCoordinates(TranslatePoint(point, content), content)); if ((list != null) && (list.Count > 0)) { foreach (UIElement element2 in list) { if (element2 is DragFillContextMenuItem) { return((DragFillContextMenuItem)element2); } } } } return(null); }
private static void OnElementHolding(object sender, HoldingRoutedEventArgs e) { if (e.HoldingState != HoldingState.Started) { return; } FrameworkElement element = sender as FrameworkElement; if (element == null) { return; } var position = e.GetPosition(element); var flyout = (MenuFlyout)FlyoutBase.GetAttachedFlyout(element); flyout.ShowAt(element, position); var itemsToCancel = VisualTreeHelper.FindElementsInHostCoordinates(position, element); foreach (var item in itemsToCancel) { item.CancelDirectManipulations(); } e.Handled = true; }
/// <summary> /// Gets the hit elements. /// </summary> /// <param name="mousePosition">The mouse position.</param> /// <returns>Enumerable of hit elements.</returns> protected virtual IEnumerable <UIElement> GetHitElements(Point mousePosition) { var element = AssociatedObject as UIElement; if (element == null) { return(Enumerable.Empty <UIElement>()); } #if SILVERLIGHT var mousePositionOffset = element.TransformToVisual(Application.Current.RootVisual).Transform(mousePosition); return(VisualTreeHelper.FindElementsInHostCoordinates(mousePositionOffset, element)); #else var elements = new List <UIElement>(); VisualTreeHelper.HitTest(element, null, hit => { if (hit.VisualHit is UIElement) { elements.Add((UIElement)hit.VisualHit); } return(HitTestResultBehavior.Continue); }, new PointHitTestParameters(mousePosition)); return(elements); #endif }
private async Task RecognizeInkerText() { System.Diagnostics.Debug.WriteLine("RecognizeInkerText"); try { var inkRecognizer = new InkRecognizerContainer(); var recognitionResults = await inkRecognizer.RecognizeAsync(inker.InkPresenter.StrokeContainer, InkRecognitionTarget.All); List <TextBox> textBoxes = new List <TextBox>(); string value = string.Empty; foreach (var result in recognitionResults) { if (TargetTextControl == null) { Point p = new Point(result.BoundingRect.X, result.BoundingRect.Y); Size s = new Size(result.BoundingRect.Width, result.BoundingRect.Height); Rect r = new Rect(p, s); var elements = VisualTreeHelper.FindElementsInHostCoordinates(r, contentPresenter); TextBox box = elements.Where(el => el is TextBox && (el as TextBox).IsEnabled).FirstOrDefault() as TextBox; if (box != null) { if (!textBoxes.Contains(box)) { textBoxes.Add(box); box.Text = ""; } if (string.IsNullOrEmpty(box.Text) == false) { box.Text += " "; } box.Text += result.GetTextCandidates().FirstOrDefault().Trim(); } } else { if (string.IsNullOrEmpty(value) == false) { value += " "; } value += result.GetTextCandidates().FirstOrDefault().Trim(); } } if (TargetTextControl != null) { var type = TargetTextControl.GetType(); PropertyInfo pInfo = type.GetProperty(TEXT_PROPERTY_NAME); pInfo.SetValue(TargetTextControl, value); } inker.InkPresenter.StrokeContainer.Clear(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } }
private object FindData(UIElement parent, Point position) { if (this.DataType == null) { return(null); } var elements = VisualTreeHelper.FindElementsInHostCoordinates(position, parent); foreach (var element in elements.Concat(new List <UIElement> { parent })) { if (this.DataType.IsInstanceOfType(element)) { return(element); } if (element is FrameworkElement && this.DataType.IsInstanceOfType(((FrameworkElement)element).DataContext)) { return(((FrameworkElement)element).DataContext); } if (element is ContentControl && this.DataType.IsInstanceOfType(((ContentControl)element).Content)) { return(((ContentControl)element).Content); } } return(null); }
void FindElementsInHostCoordinates_Demo_PointerPressed(object sender, MouseButtonEventArgs e) { // Get the absolute coordinates of the pointer: Point currentPoint = e.GetPosition(null); #else void FindElementsInHostCoordinates_Demo_PointerPressed(object sender, PointerRoutedEventArgs e) { // Get the absolute coordinates of the pointer: Point currentPoint = e.GetCurrentPoint(null).Position; #endif // Find the element that is under the pointer: var uiElement = VisualTreeHelper.FindElementsInHostCoordinates(currentPoint, CanvasParent).FirstOrDefault(); // Bring the clicked element to the front: if (uiElement is Border) { _highestZIndex++; Canvas.SetZIndex(uiElement, _highestZIndex); } } void InitAllZIndex() { // 0 -> 2 is from the background to the front Canvas.SetZIndex(BlueRectangle, 0); Canvas.SetZIndex(GreenRectangle, 1); Canvas.SetZIndex(YellowRectangle, 2); }
private void determineBoundElements() { var gt = edges.TransformToVisual(Window.Current.Content); var gtTopLeft = gt.TransformPoint(new Point(0, 0)); var boundingRect = new Rect(gtTopLeft.X, gtTopLeft.Y, edges.ActualWidth, edges.ActualHeight); var foundElements = VisualTreeHelper.FindElementsInHostCoordinates(boundingRect, _foundSelectedPageContent, true); var stampCount = 0; lpMain.AllowedListOfEntities.Clear(); if (foundElements?.Count() > 0) { var stampInstances = foundElements.Where(x => ((FrameworkElement)x).Name.Contains("stamp_")); if (stampInstances?.Count() > 0) { foreach (FrameworkElement si in stampInstances) { lpMain.AllowedListOfEntities.Add(si.Name); } stampCount = stampInstances.Count(); } } elDebug.Text = $@"x: {gtTopLeft.X.ToString("F0", CultureInfo.InvariantCulture)} y: {gtTopLeft.Y.ToString("F0", CultureInfo.InvariantCulture)} width: {edges.ActualWidth.ToString("F0", CultureInfo.InvariantCulture)} height: {edges.ActualHeight.ToString("F0", CultureInfo.InvariantCulture)} stamp count: {stampCount}"; }
private void AssociatedObject_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) { if (PreviewBehavior._isShowingPreview) { Point point = new Point(e.ManipulationOrigin.X, e.ManipulationOrigin.Y); UIElement rootVisual = Application.Current.RootVisual; FrameworkElement newHoveredElement = VisualTreeHelper.FindElementsInHostCoordinates(PreviewBehavior.GetHostCoordinates(e.ManipulationContainer.TransformToVisual(rootVisual).Transform(point)), rootVisual).FirstOrDefault <UIElement>() as FrameworkElement; if (newHoveredElement != null) { BehaviorCollection behaviors1 = Interaction.GetBehaviors((DependencyObject)newHoveredElement); PreviewBehavior previewBehavior = (behaviors1 != null ? behaviors1.FirstOrDefault <Behavior>((Func <Behavior, bool>)(b => b is PreviewBehavior)) : (Behavior)null) as PreviewBehavior; if (previewBehavior == null && newHoveredElement.Parent != null) { BehaviorCollection behaviors2 = Interaction.GetBehaviors(newHoveredElement.Parent); previewBehavior = (behaviors2 != null ? behaviors2.FirstOrDefault <Behavior>((Func <Behavior, bool>)(b => b is PreviewBehavior)) : (Behavior)null) as PreviewBehavior; } if (previewBehavior != null) { Image image = newHoveredElement as Image; BitmapImage originalImage = (image != null ? image.Source : null) as BitmapImage; this.ShowPreview(previewBehavior.PreviewUri, originalImage, previewBehavior.TopOffset); this.SetHoveredElement(newHoveredElement); } } e.Handled = true; } else { this.StopTimer(); } }
void elementToDrag_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { UIElement element = (UIElement)sender; TranslateTransform transform = GetTranslateTransform(element); Point currentMousePosition = e.GetPosition(layoutRoot); double mouseX = currentMousePosition.X - lastMousePosition.X; double mouseY = currentMousePosition.Y - lastMousePosition.Y; transform.X += mouseX; transform.Y += mouseY; if (Collision != null) { List <UIElement> collidedElements = VisualTreeHelper.FindElementsInHostCoordinates(currentMousePosition, layoutRoot) as List <UIElement>; collidedElements.Remove(element); collidedElements.Remove(layoutRoot); if (collidedElements.Count() > 0) { CollisionEventArgs args = new CollisionEventArgs() { Element = element, Position = currentMousePosition, CollidedElements = collidedElements }; Collision(this, args); } } lastMousePosition = currentMousePosition; } }
private DependencyObject GetReactViewTarget(PointerRoutedEventArgs e) { // Ensure the original source is a DependencyObject var originalSource = e.OriginalSource as DependencyObject; if (originalSource == null) { return(null); } // Get the React view hierarchy from the original source. var enumerator = RootViewHelper.GetReactViewHierarchy(originalSource).GetEnumerator(); // Try to get the first React view. if (!enumerator.MoveNext()) { return(null); } // If the first React view has `pointerEvents: box-none`, revert // to using the `VisualTreeHelper` to find potentially occluded views. // This condition should be rare. if (enumerator.Current.GetPointerEvents() == PointerEvents.BoxNone) { var rootPoint = e.GetCurrentPoint(_view); var transform = _view.TransformToVisual(Window.Current.Content); var point = transform.TransformPoint(rootPoint.Position); var adjustedPoint = AdjustPointForStatusBar(point); // Get the first view in at the pointer point that is not `box-none`. var nonBoxOnlyView = VisualTreeHelper.FindElementsInHostCoordinates(adjustedPoint, _view) .First(v => v.HasTag() && v.GetPointerEvents() != PointerEvents.BoxNone); // Update the enumerator for the non-`box-only` view. enumerator = RootViewHelper.GetReactViewHierarchy(nonBoxOnlyView).GetEnumerator(); if (!enumerator.MoveNext()) { return(null); } } // Views with `pointerEvents: none` are not hit test enabled, so we // will not encounter any view subtrees with this value. Given the // prior conditional for `pointerEvents: box-none`, we only need to // loop through the parents of the current React view target to // check for uses of `pointerEvents: box-only`. If found, the // parent becomes the new target. var source = enumerator.Current; while (enumerator.MoveNext()) { var current = enumerator.Current; if (source == null || current.GetPointerEvents() == PointerEvents.BoxOnly) { source = current; } } return(source); }
private void MainCanvas_Tapped(object sender, TappedRoutedEventArgs e) { if (e.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Pen) { return; } var position = e.GetPosition(Root); List <UIElement> elements = new List <UIElement>(VisualTreeHelper.FindElementsInHostCoordinates(position, MainCanvas)); if (elements.Count > 0) { return; } RichEditBox box = new RichEditBox(); box.Width = Root.Width > 500 ? Math.Min(Root.ActualWidth / 2, 500) : Root.Width; box.LostFocus += Box_LostFocus; box.SizeChanged += Box_SizeChanged; box.Style = App.Current.Resources["InfiniteRichEditBoxStyle"] as Style; Canvas.SetLeft(box, position.X); Canvas.SetTop(box, position.Y); MainCanvas.Children.Add(box); box.Focus(FocusState.Keyboard); AdjustCanvasSize(); }
public static void ScrollItem(ListViewBase control, int indexDelta) { if (control == null || control.Items == null) { return; } var scrollViewer = VisualTreeUtilities.GetVisualChild <ScrollViewer>(control); var p = new Point(Window.Current.Bounds.Width / 2, 10); var transform = control.TransformToVisual(Window.Current.Content); var checkPoint = transform.TransformPoint(p); var q = from lvi in VisualTreeHelper.FindElementsInHostCoordinates(checkPoint, scrollViewer).OfType <ListViewItem>() where lvi.Content != null select lvi.Content; var item = q.FirstOrDefault(); if (item == null) { return; } var index = control.Items.IndexOf(item); var nextItemIndex = index + indexDelta; if (index != -1 && nextItemIndex >= 0 && nextItemIndex < control.Items.Count) { var nextItem = control.Items[nextItemIndex]; control.ScrollIntoView(nextItem, ScrollIntoViewAlignment.Leading); } }
void OnPointerEnteredMoved(object sender, PointerRoutedEventArgs e) { //validate if (!EnableHoverSelection) { return; } //find all highlightables under the cursor var overlayInfos = VisualTreeHelper.FindElementsInHostCoordinates(e.GetCurrentPoint(null).Position, _contentGrid).OfType <OverlayControl>().Select(i => i.OverlayInfo).Where(i => i != null && (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse || e.Pointer.IsInContact)); //test for touch exit event _hasPresenterSelected = true; //highlight new items foreach (var highlightable in overlayInfos.Except(_presenterSelected)) { _presenterSelected.Add(highlightable); highlightable.IsSelected = true; } //unhighlight old items foreach (var highlightable in _presenterSelected.Except(overlayInfos).ToArray()) { _presenterSelected.Remove(highlightable); highlightable.IsSelected = false; } _hasPresenterSelected = false; }
private void OnPointerReleased(object sender, PointerRoutedEventArgs pointerRoutedEventArgs) { // Get the primary touch point. We do not track multitouch at the moment. var primaryTouchPoint = pointerRoutedEventArgs.GetCurrentPoint(Windows.UI.Xaml.Window.Current.Content); var uiElements = VisualTreeHelper.FindElementsInHostCoordinates(primaryTouchPoint.Position, Windows.UI.Xaml.Window.Current.Content); foreach (var uiElement in uiElements) { // Are we interested? var renderer = uiElement as NControlViewRenderer; if (renderer == null) { continue; } // Get NControlView element var element = renderer.Element; // Get this' position on screen var transform = Windows.UI.Xaml.Window.Current.Content.TransformToVisual(renderer.Control); // Transform touches var touchPoints = pointerRoutedEventArgs.GetIntermediatePoints(Windows.UI.Xaml.Window.Current.Content); var touches = touchPoints .Select(t => transform.TransformPoint(new Windows.Foundation.Point(t.Position.X, t.Position.Y))) .Select(t => new NGraphics.Point(t.X, t.Y)).ToList(); if (element.TouchesEnded(touches)) { break; } } }
void selectedEntry_DragMoved(object sender, MouseEventArgs e) { VideoPanelEntry entry = sender as VideoPanelEntry; IEnumerable <UIElement> hitTestResult = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition((Application.Current.RootVisual as Page).VideoArea), (Application.Current.RootVisual as Page).VideoArea); bool _foundVideoPanelEntry = false; foreach (UIElement hitElement in hitTestResult) { if ((!_foundVideoPanelEntry) && (hitElement.Equals(entry))) { _foundVideoPanelEntry = true; } else { if (hitElement.Equals(this)) { entry.DragAndDropState = VideoPanelEntryDragAndDropState.NoDrop; break; } if (hitElement is VideoPlayer) { entry.DragAndDropState = VideoPanelEntryDragAndDropState.Move; break; } // if we get to the VideoArea Canvas, then nothing else was hit if (hitElement.Equals((Application.Current.RootVisual as Page).VideoArea)) { entry.DragAndDropState = VideoPanelEntryDragAndDropState.Add; break; } } } }
private void ControlOnManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e) { if (_frame == null) { return; } MainContainer.Children.Remove(_frame); _frame = null; //var diffPos = e.Cumulative.Translation; //var pos = e.Position; var pos = new Point(_startPoint.X + e.Cumulative.Translation.X, _startPoint.Y + e.Cumulative.Translation.Y); //Debug.WriteLine(pos); //Debug.WriteLine(new Point(_startPoint.X + e.Cumulative.Translation.X, _startPoint.Y + e.Cumulative.Translation.Y)); //new Point(_startPoint.X +e., _startPoint.Y) var elements = VisualTreeHelper.FindElementsInHostCoordinates(pos, GetCurrentPage(), true); Debug.WriteLine("Found elements:"); foreach (var element in elements) { if (!(element is FrameworkElement frameworkElement)) { Debug.WriteLine($"{element.GetType().Name}"); continue; } Debug.WriteLine($"{element.GetType().Name}: {frameworkElement.Name}"); } Debug.WriteLine(""); }
private async void Sv_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { await Dispatcher.TryRunAsync(CoreDispatcherPriority.Normal, delegate { ScrollViewer sv = sender as ScrollViewer; GeneralTransform gt = sv.TransformToVisual(this); Point p = gt.TransformPoint(new Point(0, 0)); List <UIElement> list = new List <UIElement>(VisualTreeHelper.FindElementsInHostCoordinates(p, sv)); ListViewItem item = list.OfType <ListViewItem>().FirstOrDefault(); if (item != null) { int index = mylist.IndexFromContainer(item); //Debug.WriteLine("Visible item at top of list is " + index); var meds = mylist.ItemsSource as GenerateHomePage <InstaMedia>; foreach (InstaMedia med in meds) { if (med.Play) { med.Play = false; } } ((InstaMedia)meds[index]).Play = true; } }); }
protected override void OnHolding(HoldingRoutedEventArgs e) { // Responding to HoldingState.Started will show a context menu while your finger is still down, while // HoldingState.Completed will wait until the user has removed their finger. if (e.HoldingState == Windows.UI.Input.HoldingState.Completed) { var PointerPosition = e.GetPosition(null); var MyObject = (e.OriginalSource as FrameworkElement).DataContext as SampleDataModel; ShowContextMenu(MyObject, null, PointerPosition); e.Handled = true; // This, combined with a check in OnRightTapped prevents the firing of RightTapped from // launching another context menu _IsPointerPressed = false; // This prevents any scrollviewers from continuing to pan once the context menu is displayed. // Ideally, you should find the ListViewItem itself and only CancelDirectMinpulations on that item. var ItemsToCancel = VisualTreeHelper.FindElementsInHostCoordinates(PointerPosition, ItemListView); foreach (var Item in ItemsToCancel) { var Result = Item.CancelDirectManipulations(); } } base.OnHolding(e); }
private void dragShortCut_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { isDrag = false; dragShortCut.ReleaseMouseCapture(); dragShortCut.Visibility = System.Windows.Visibility.Collapsed; Debug.WriteLine("dragShortCut_MouseLeftButtonUp__false"); if (isDelete) { isDelete = false; #region 检测删除面板 var startMenuS = from element in VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), gridBottom) where element is SMT.SAAS.Platform.Xamls.MainPagePart.Start select element; if (startMenuS.Count() >= 1) { SMT.SAAS.Platform.Xamls.MainPagePart.Start start = startMenuS.FirstOrDefault() as SMT.SAAS.Platform.Xamls.MainPagePart.Start; if (start != null) { ViewModel.MainPage.ShortCutViewModel shortcutVM = (dragShortCut.DataContext as ViewModel.MainPage.ShortCutViewModel); shortCutManager.RemoveItem(shortcutVM.ShortCutID); } } #endregion } else { #region 检测添加面板 var ShortCutManagers = from element in VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), grdShortCut) where element is SMT.SAAS.Platform.Xamls.MainPagePart.ShortCutManager select element; if (ShortCutManagers.Count() >= 1) { SMT.SAAS.Platform.Xamls.MainPagePart.ShortCutManager customMenus = ShortCutManagers.FirstOrDefault() as SMT.SAAS.Platform.Xamls.MainPagePart.ShortCutManager; if (customMenus != null) { ViewModel.Menu.MenuViewModel menuvm = (dragShortCut.DataContext as ViewModel.Menu.MenuViewModel); ViewModel.MainPage.ShortCutViewModel vm = new ViewModel.MainPage.ShortCutViewModel() { AssemplyName = menuvm.Content.ModuleType == null ? "NULL" : menuvm.Content.ModuleType, FullName = menuvm.Content.ModuleType == null ? "NULL" : menuvm.Content.ModuleType, Titel = menuvm.MenuName, IconPath = menuvm.MenuIconPath, ModuleID = menuvm.MenuID, ShortCutID = menuvm.MenuID, IsSysNeed = "0", ModuleName = menuvm.Content.ModuleName, UserState = "1" }; customMenus.AddItem(vm); } } #endregion } }
public MovableContentControl[] IntersectWith() { var parent = VisualTreeHelper.GetParent(this) as Canvas; var boundingRect = new Rect(Canvas.GetLeft(this), Canvas.GetTop(this), Width, Height); return(VisualTreeHelper.FindElementsInHostCoordinates(boundingRect, parent).Where(_ => _ is MovableContentControl).Select(_ => _ as MovableContentControl).ToArray()); }
/// <summary> /// Return whether the gaze point is over the progress bar. /// </summary> /// <param name="gazePoint">The gaze point screen location</param> /// <param name="elementName">The progress bar name</param> /// <param name="uiElement">The progress bar UI element</param> /// <returns></returns> private bool DoesElementContainPoint( Windows.Foundation.Point gazePoint, string elementName, UIElement uiElement) { // Use entire visual tree of progress bar. IEnumerable <UIElement> elementStack = VisualTreeHelper.FindElementsInHostCoordinates(gazePoint, uiElement, true); foreach (UIElement item in elementStack) { //Cast to FrameworkElement and get element name. if (item is FrameworkElement feItem) { if (feItem.Name.Equals(elementName)) { if (!timerStarted) { // Start gaze timer if gaze over element. timerGaze.Start(); timerStarted = true; } return(true); } } } // Stop gaze timer and reset progress bar if gaze leaves element. timerGaze.Stop(); GazeRadialProgressBar.Value = 0; timerStarted = false; return(false); }
private async Task RecognizeInkerText() { var inkRecognizer = new InkRecognizerContainer(); var recognitionResults = await inkRecognizer.RecognizeAsync(Inker.InkPresenter.StrokeContainer, InkRecognitionTarget.All); List <TextBox> boxes = new List <TextBox>(); foreach (var result in recognitionResults) { List <UIElement> elements = new List <UIElement>( VisualTreeHelper.FindElementsInHostCoordinates( new Rect(new Point(result.BoundingRect.X, result.BoundingRect.Y), new Size(result.BoundingRect.Width, result.BoundingRect.Height)), this)); TextBox box = elements.Where(el => el is TextBox && (el as TextBox).IsEnabled).FirstOrDefault() as TextBox; if (box != null) { if (!boxes.Contains(box)) { boxes.Add(box); box.Text = ""; } box.Text += " " + result.GetTextCandidates().FirstOrDefault().Trim(); } } Inker.InkPresenter.StrokeContainer.Clear(); }
/// <summary> /// Recognizes the inker text. /// </summary> /// <returns></returns> private async Task RecognizeInkerText() { try { InkRecognizerContainer inkRecognizer = new InkRecognizerContainer(); IReadOnlyList <InkRecognitionResult> recognitionResults = await inkRecognizer.RecognizeAsync(this.inker.InkPresenter.StrokeContainer, InkRecognitionTarget.All); string value = string.Empty; foreach (var result in recognitionResults) { Point p = new Point(result.BoundingRect.X, result.BoundingRect.Y); Size s = new Size(result.BoundingRect.Width, result.BoundingRect.Height); Rect r = new Rect(p, s); GeneralTransform gt = this.TransformToVisual(Window.Current.Content); var r2 = gt.TransformBounds(r); var elements = VisualTreeHelper.FindElementsInHostCoordinates(r2, (UIElement)this.Content, true); TextBox box = elements.FirstOrDefault(el => el is TextBox && (el as TextBox).IsEnabled) as TextBox; if (box != null) { box.Text += result.GetTextCandidates().FirstOrDefault().Trim() + " "; } } this.inker.InkPresenter.StrokeContainer.Clear(); } catch { } }
Cell FindCell(GestureEventArgs e, out FrameworkElement element) { Cell cell = null; element = e.OriginalSource as FrameworkElement; if (element != null) { cell = element.DataContext as Cell; } if (cell == null) { System.Windows.Point pos = e.GetPosition(_listBox); IEnumerable <UIElement> elements = VisualTreeHelper.FindElementsInHostCoordinates(pos, _listBox); foreach (FrameworkElement frameworkElement in elements.OfType <FrameworkElement>()) { if ((cell = frameworkElement.DataContext as Cell) != null) { element = frameworkElement; break; } } } return(cell); }
void catalogSlideView_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e) { var list = VisualTreeHelper.FindElementsInHostCoordinates(new Rect(new Point(0, 0), new Point(800, 480)), catalogSlideView).OfType <ListBoxItem>(); if (list.Any()) { CatalogPageItem ListBoxItemInFocus = null; var count = list.Count(); if (count == 1) { ListBoxItemInFocus = list.First().Content as CatalogPageItem; } else { int value = (int)Math.Ceiling(count / 2d); ListBoxItemInFocus = list.ToList()[value].Content as CatalogPageItem; } model.CurrentPage = ListBoxItemInFocus.Id; } //foreach (var item in catalogSlideView.Items) //{ // var isVisible = TestVisibility(item, catalogSlideView, System.Windows.Controls.Orientation.Vertical, true); // if (isVisible) // { // int bbbb = 0; // } //} GC.Collect(); GC.WaitForPendingFinalizers(); }
/// <summary> /// Finds some (but maybe not all) of the map elements associated with a point. /// </summary> /// <param name="pos">The point at which to check for associated map elements</param> /// <returns>An enumerable list of associated map elements</returns> public IEnumerable <UIElement> ElementsAtPoint(Point pos) { var eleList = new List <UIElement>(); var elements = VisualTreeHelper.FindElementsInHostCoordinates(pos, TheMap, false); try { var count = 0; var length = elements.Count(); // Elements can have several hundred elements but throws an EETypeLoadException // after four elements have been enumerated. Four is enough for us. foreach (var element in elements) { eleList.Add(element); if (++count > 3) { break; } } } catch (Exception ex) { Log.WriteMessage(LogLevel.Warn, "Error reading list of elements at host coordinates", ex); } return(eleList); }
void PageLoaded(object sender, RoutedEventArgs routedEventArgs) { DataContext = new MainPageViewModel(); ViewModel = DataContext as MainPageViewModel; ImageGridView.Loaded += (sender3, args3) => { ImageGridView.RightTapped += (o, eventArgs) => { eventArgs.Handled = false; var elements = VisualTreeHelper.FindElementsInHostCoordinates(eventArgs.GetPosition(o as UIElement), ImageGridView); var imageView = elements.First((x) => x.GetType() == typeof(ImageEx)) as ImageEx; Debug.WriteLine("imageView is " + imageView); ViewModel.ImageContextOpened = imageView.DataContext as FullImageViewModel; }; }; if (ImageGridView.Items?.Count > 0 && GlobalInfo.SelectedImage > 0 && GlobalInfo.SelectedImage <= ImageGridView.Items.Count - 1) { ImageGridView.ScrollIntoView(ImageGridView.Items[GlobalInfo.SelectedImage]); } Debug.WriteLine("Image count in gridview is " + ImageGridView.Items.Count); Debug.WriteLine("Image count in GlobalInfo is " + GlobalInfo.CurrentSearch.Count); Debug.WriteLine("Image count in GlobalInfo ViewModels is " + GlobalInfo.ImageViewModels.Count); }
/// <summary> /// Handler timer ticks. /// </summary> /// <param name="sender">Timer.</param> /// <param name="e">EventArgs.</param> private void OnTimeout(object sender, EventArgs e) { int interval = Interval; if (_timer.Interval.Milliseconds != interval) { _timer.Interval = TimeSpan.FromMilliseconds(interval); } if (IsPressed) { if (_keyboardCausingRepeat) { // if the timeout occurred when the space key was down // trigger the click directly without running a hit test. OnClick(); } else { // this is a workaround to check the HitTest to see // whether the mouse is still over the button, since // Silverlight has a bug where MouseEnter/MouseLeave // states are not detected until the mouse has moved. foreach (UIElement element in VisualTreeHelper.FindElementsInHostCoordinates(_mousePosition, this)) { if (element == _elementRoot) { OnClick(); } } } } }