/// <summary> /// Occurs when the element is laid out, rendered, and ready for interaction. /// </summary> /// <param name="sender">The object where the event handler is attached.</param> /// <param name="e">The event data.</param> void OnLoaded(Object sender, RoutedEventArgs e) { // The GadgetBar is actually not part of the ExplorerPage even though its resources are declared here. When the ExplorerPage is hooked into the // ExplorerFrame, the frame gets a message asking it to use the GadgetBar (which is really just an ObservableCollection of Gadgets) as the ItemsSource // in the ExplorerBar control on the frame. So The GadgetBar property in this control is really just a collection that is used by the main frame window // of the application. As such, it has no way of routing commands back to the ExplorerPage where the Gadget was declared. If we left the CommandTarget // alone, the Command Routing would attempt to find the element with the focus, but that is too random for most high level, application-type commands. // This will direct every Gadget with a command, that has a corresponding CommandBinding, to target this page when the command is invoked. foreach (Gadget gadget in this.GadgetBar) { foreach (CommandBinding commandBinding in this.CommandBindings) { if (gadget.Command == commandBinding.Command && gadget.CommandTarget == null) { gadget.CommandTarget = this; } } } // The data context for the page is the item selected in the frame. ExplorerFrame explorerFrame = VisualTreeExtensions.FindAncestor <ExplorerFrame>(this); if (explorerFrame != null) { this.DataContext = explorerFrame.SelectedItem; } // This will send a message up to the frame that there is a new set of gadgets available. The frame will use this instance's collection directly so // that changing the local collection here will change the way the gadgets are displayed in the frame's toolbar. if (this.GadgetBar.Count != 0) { this.RaiseEvent(new ItemsSourceEventArgs(ExplorerFrame.GadgetBarChangedEvent, this.GadgetBar)); } }
private void itemsControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (CurrentViewMode == MainControls.CurrentViewMode.ArtistDetails || CurrentViewMode == MainControls.CurrentViewMode.ComposerDetails) { if (e.LeftButton == MouseButtonState.Pressed) { ListBoxItem item = VisualTreeExtensions.FindParent <ListBoxItem>(e.OriginalSource as DependencyObject); if (item != null) { TrackListItem tli = item.DataContext as TrackListItem; PersonGroup personGroup = DataBase.GetPersonGroupByName(tli.Name, false); PersonGroupWindow personGroupWindow = new PersonGroupWindow(DataBase, CurrentViewMode == MainControls.CurrentViewMode.ArtistDetails ? PersonType.Artist : PersonType.Composer, personGroup); personGroupWindow.ChangeAllSoundFiles = true; personGroupWindow.Owner = Window.GetWindow(this); personGroupWindow.ShowDialog(); UpdateTrackListItem(tli); } } } }
public async Task SortTest02() { VisualTreeObject actual = null; using (var hostScript = new VariableRHostScript()) { using (var script = new ControlTestScript(typeof(VariableGridHost))) { await PrepareControl(hostScript, script, "grid.test <- mtcars"); await UIThreadHelper.Instance.InvokeAsync(async() => { var grid = await VisualTreeExtensions.FindChildAsync <VisualGrid>(script.Control); var header = await VisualTreeExtensions.FindChildAsync <HeaderTextVisual>(script.Control); // mpg header = await VisualTreeExtensions.FindNextSiblingAsync <HeaderTextVisual>(header); // cyl header.Should().NotBeNull(); grid.ToggleSort(header, false); DoIdle(200); header = await VisualTreeExtensions.FindNextSiblingAsync <HeaderTextVisual>(header); // disp header = await VisualTreeExtensions.FindNextSiblingAsync <HeaderTextVisual>(header); // hp grid.ToggleSort(header, add: true); grid.ToggleSort(header, add: true); DoIdle(200); }); actual = VisualTreeObject.Create(script.Control); ViewTreeDump.CompareVisualTrees(_files, actual, "VariableGridSorted02"); } } }
private void SearchPictureButton_Click(object sender, RoutedEventArgs e) { ListBoxItem lbi = VisualTreeExtensions.FindParent <ListBoxItem>(e.OriginalSource as DependencyObject); PersonGroupViewItem pgvi = lbi.DataContext as PersonGroupViewItem; Canvas overlayPopupCanvas = VisualTreeExtensions.FindVisualChildByName <Canvas>(Window.GetWindow(this), "OverlayPopupCanvas"); PictureSearchUserControl pictureSearchPopup = new PictureSearchUserControl(); pictureSearchPopup.Width = 620; pictureSearchPopup.Height = 180; DropShadowEffect dse = new DropShadowEffect(); dse.Color = Colors.LightGray; pictureSearchPopup.Effect = dse; overlayPopupCanvas.Children.Clear(); overlayPopupCanvas.Children.Add(pictureSearchPopup); pictureSearchPopup.SetValue(Canvas.TopProperty, Mouse.GetPosition(overlayPopupCanvas).Y); pictureSearchPopup.SetValue(Canvas.LeftProperty, Mouse.GetPosition(overlayPopupCanvas).X); overlayPopupCanvas.Visibility = System.Windows.Visibility.Visible; pictureSearchPopup.Search(pgvi.Name); pictureSearchPopup.PictureSelected += new EventHandler(PictureSearchPopup_PictureSelected); pictureSearchPopup.CloseClicked += new EventHandler(PictureSearchPopup_CloseClicked); }
private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (VisualTreeExtensions.FindParent <DataGridRow>(e.OriginalSource as DependencyObject) != null) { AlbumListItem item = dataGrid.SelectedItem as AlbumListItem; if (item != null) { switch (CurrentViewMode) { case CurrentViewMode.MediumTable: { ChangeViewCommandParameters changeViewParams = new ChangeViewCommandParameters(); changeViewParams.ViewMode = MainControls.CurrentViewMode.AlbumTable; Big3.Hitbase.DataBaseEngine.Condition condition = new Big3.Hitbase.DataBaseEngine.Condition(); condition.Add(new SingleCondition(Field.Medium, Operator.Equal, item.Title)); changeViewParams.Condition = condition; CatalogViewCommands.ChangeView.Execute(changeViewParams, this); break; } } } } }
void PictureSearchPopup_CloseClicked(object sender, EventArgs e) { Canvas overlayPopupCanvas = VisualTreeExtensions.FindVisualChildByName <Canvas>(Window.GetWindow(this), "OverlayPopupCanvas"); overlayPopupCanvas.Children.Clear(); overlayPopupCanvas.Visibility = System.Windows.Visibility.Collapsed; }
void PictureSearchPopup_PictureSelected(object sender, EventArgs e) { PictureSearchUserControl psp = sender as PictureSearchUserControl; if (psp.SelectedItem != null) { BitmapImage bi = psp.DownloadSelectedImage(); if (bi != null) { PersonGroupViewItem pgvi = itemsControl.SelectedItem as PersonGroupViewItem; string filename = Misc.GetCDCoverFilename(Misc.FilterFilenameChars(pgvi.Name) + ".jpg"); FileStream stream = new FileStream(filename, FileMode.Create); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 30; encoder.Frames.Add(BitmapFrame.Create(bi)); encoder.Save(stream); stream.Close(); DataBase.SetPersonGroupImage(pgvi.ID, filename); UpdateRow(pgvi); } } Canvas overlayPopupCanvas = VisualTreeExtensions.FindVisualChildByName <Canvas>(Window.GetWindow(this), "OverlayPopupCanvas"); overlayPopupCanvas.Children.Clear(); overlayPopupCanvas.Visibility = System.Windows.Visibility.Collapsed; }
private void Grid_MouseEnter(object sender, MouseEventArgs e) { Button searchPictureButton = VisualTreeExtensions.FindVisualChildByName <Button>(sender as DependencyObject, "SearchPictureButton"); if (searchPictureButton == null) { searchPictureButton = FindResource("mySearchPictureButton") as Button; theGrid.Children.Add(searchPictureButton); } Button showPictureButton = VisualTreeExtensions.FindVisualChildByName <Button>(sender as DependencyObject, "ShowPictureButton"); if (showPictureButton == null) { showPictureButton = FindResource("myShowPictureButton") as Button; theGrid.Children.Add(showPictureButton); } if (this.buttonChoosePicture.Visibility == System.Windows.Visibility.Visible) { searchPictureButton.BeginAnimation(Button.OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(500).Duration())); searchPictureButton.Visibility = System.Windows.Visibility.Visible; showPictureButton.Visibility = System.Windows.Visibility.Collapsed; } else { showPictureButton.BeginAnimation(Button.OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(500).Duration())); searchPictureButton.Visibility = System.Windows.Visibility.Collapsed; showPictureButton.Visibility = System.Windows.Visibility.Visible; } }
private void SearchImage() { PictureSearchPopup pictureSearchPopup = new PictureSearchPopup(); pictureSearchPopup.PopupAnimation = System.Windows.Controls.Primitives.PopupAnimation.Fade; pictureSearchPopup.IsOpen = true; pictureSearchPopup.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom; Button searchPictureButton = VisualTreeExtensions.FindVisualChildByName <Button>(this, "SearchPictureButton"); if (searchPictureButton != null) { pictureSearchPopup.PlacementTarget = searchPictureButton; } else { pictureSearchPopup.PlacementTarget = this; } pictureSearchPopup.Width = 640; pictureSearchPopup.Height = 200; pictureSearchPopup.StaysOpen = false; pictureSearchPopup.PictureSelected += new EventHandler(pictureSearchPopup_PictureSelected); string searchText = GetSearchText(); pictureSearchPopup.Search(searchText); }
/// <summary> /// Occurs when the element is laid out, rendered, and ready for interaction. /// </summary> /// <param name="sender">The object where the event handler is attached.</param> /// <param name="routedEventArgs">The event data.</param> void OnLoaded(Object sender, RoutedEventArgs routedEventArgs) { // This object will automatically bind itself to a parent TreeFrame when one is available. ExplorerFrame explorerFrame = VisualTreeExtensions.FindAncestor <ExplorerFrame>(this); if (explorerFrame != null) { // The children of a Frame do not automatically inherit the data context of the parent window. This is likely due to the fact that pages are not // naturally kept alive when the navigation moves away. So any data binding operation must be established or re-established when the page is // loaded and must be cleared when the page is unloaded. This will bind this page to the context of the parent frame (for now). Binding dataContextBinding = new Binding(); dataContextBinding.Path = new PropertyPath("DataContext"); dataContextBinding.Source = explorerFrame; dataContextBinding.Mode = BindingMode.OneWay; BindingOperations.SetBinding(this, ViewPage.DataContextProperty, dataContextBinding); // The Source property binding allows a change to the property to propogate up to the container. Binding sourceBinding = new Binding(); sourceBinding.Path = new PropertyPath("Source"); sourceBinding.Source = explorerFrame; sourceBinding.Mode = BindingMode.TwoWay; BindingOperations.SetBinding(this, ViewPage.SourceProperty, sourceBinding); // This value indicates what kind of view is used to display the items. Binding viewValueBinding = new Binding(); viewValueBinding.Path = new PropertyPath("ViewValue"); viewValueBinding.Source = explorerFrame; viewValueBinding.Mode = BindingMode.TwoWay; BindingOperations.SetBinding(this, ViewPage.ViewValueProperty, viewValueBinding); } }
private void AddButtonClicked() { try { var parent = VisualTreeExtensions.FindParent <MainCalendarView>(this); if (parent == null) { throw new NullReferenceException("Couldn't find parent."); } CalendarViewModel viewModel = parent.ViewModel; if (viewModel == null) { throw new NullReferenceException("Parent's view model was null"); } App.ShowFlyoutAddHomeworkOrExam( elToCenterFrom: _addButton, addHomeworkAction: delegate { viewModel.AddHomework(base.Date); }, addExamAction: delegate { viewModel.AddExam(base.Date); }, addHolidayAction: delegate { viewModel.AddHoliday(base.Date); }); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
/// <summary> /// Invoked when an unhandled Mouse.MouseMove attached event reaches an element in its route that is derived from this class. /// </summary> /// <param name="e">The MouseEventArgs that contains the event data.</param> protected override void OnMouseMove(MouseEventArgs e) { // Validate the parameters. if (e == null) { throw new ArgumentNullException("e"); } // This will highlight (and bring comletely into view) the element underneath the mouse. There is a verion of this in the WPF ComboBox that waits for a // MouseEnter event from the element and then tries to figure out if mouse movement caused the event. This is cumbersome because a MouseEnter event can // be caused by the mouse being moved over the element, or the element being scrolled underneath the mouse. An element being scrolled underneath a // mouse that hasn't moved can cause a false highlighting of the element, so a whole 'nuther set of logic was required to see if the mouse had actually // moved. Since this event assumes that the mouse has moved, it is simpler just to find out what element is under the mouse and change the highlight if // it wasn't the last thing highlighted. DependencyObject dependencyObject = this.InputHitTest(e.GetPosition(this)) as DependencyObject; HighlightElement highlightElement = VisualTreeExtensions.FindAncestor <HighlightElement>(dependencyObject); if (highlightElement != this.HighlightedElement) { highlightElement.BringIntoView(); this.HighlightedElement = highlightElement; } // Because an intermediate class in the inheritance might implement this method, we recommend that you call the base implementation in your // implementation. base.OnMouseMove(e); }
/// <summary> /// When overridden in a derived class, participates in rendering operations that are directed by the layout system. /// The rendering instructions for this element are not used directly when this method is invoked, and are instead preserved for /// later asynchronous use by layout and drawing. /// </summary> /// <param name="drawingContext">The drawing instructions for a specific element. This context is provided to the layout system.</param> protected override void OnRender(DrawingContext drawingContext) { var dropInfo = this.DropInfo; var visualTargetItem = dropInfo.VisualTargetItem; if (visualTargetItem != null) { var rect = Rect.Empty; var tvItem = visualTargetItem as TreeViewItem; if (tvItem != null && VisualTreeHelper.GetChildrenCount(tvItem) > 0) { var descendant = VisualTreeExtensions.GetVisibleDescendantBounds(tvItem); var translatePoint = tvItem.TranslatePoint(new Point(), this.AdornedElement); var itemRect = new Rect(translatePoint, tvItem.RenderSize); descendant.Union(itemRect); translatePoint.Offset(1, 0); rect = new Rect(translatePoint, new Size(descendant.Width - translatePoint.X - 1, tvItem.ActualHeight)); } if (rect.IsEmpty) { rect = new Rect(visualTargetItem.TranslatePoint(new Point(), this.AdornedElement), VisualTreeExtensions.GetVisibleDescendantBounds(visualTargetItem).Size); } drawingContext.DrawRoundedRectangle(null, this.Pen, rect, 2, 2); } }
/// <summary> /// Retrieves the visible containers in a LongListSelector and adds them to <paramref name="items"/>. /// </summary> /// <param name="list">LongListSelector that contains the items.</param> /// <param name="itemsPanel">Direct parent of the items.</param> /// <param name="items">List to populate with the containers currently in the viewport</param> /// <param name="selectContent"> /// Specifies whether to return the container or its content. /// For headers, we can't apply projections on the container directly (or everything will go blank), /// so we will apply them on the content instead. /// </param> private static void AddVisibileContainers(LongListSelector list, Canvas itemsPanel, List <KeyValuePair <double, FrameworkElement> > items, bool selectContent) { foreach (DependencyObject obj in VisualTreeExtensions.GetVisualChildren(itemsPanel)) { ContentPresenter container = obj as ContentPresenter; if (container != null && (!selectContent || (VisualTreeHelper.GetChildrenCount(container) == 1 && VisualTreeHelper.GetChild(container, 0) is FrameworkElement))) { GeneralTransform itemTransform = null; try { itemTransform = container.TransformToVisual(list); } catch (ArgumentException) { // Ignore failures when not in the visual tree break; } Rect boundingBox = new Rect(itemTransform.Transform(new Point()), itemTransform.Transform(new Point(container.ActualWidth, container.ActualHeight))); if (boundingBox.Bottom > 0 && boundingBox.Top < list.ActualHeight) { items.Add( new KeyValuePair <double, FrameworkElement>( boundingBox.Top, selectContent ? (FrameworkElement)VisualTreeHelper.GetChild(container, 0) : container)); } } } }
private void DataGridResult_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (VisualTreeExtensions.FindParent <DataGridRow>(e.OriginalSource as DependencyObject) != null) { ShowDetails(); } }
private void ButtonMultiLineEdit_Click(object sender, RoutedEventArgs e) { DataGridRow row = VisualTreeExtensions.FindParent <DataGridRow>(e.OriginalSource as DependencyObject); DataGridCell cell = VisualTreeExtensions.FindParent <DataGridCell>(e.OriginalSource as DependencyObject); Field field = (Field)cell.Column.GetValue(Big3.Hitbase.Controls.DataGridExtensions.FieldProperty); AlbumItem album = row.DataContext as AlbumItem; WindowMultiline wm = new WindowMultiline(); wm.Owner = Window.GetWindow(this); object textValue = album.Comment; if (textValue != null) { wm.Text = textValue.ToString(); } wm.Title = DataBase.GetNameOfField(field); if (wm.ShowDialog() == true) { // Im Moment hier nur Read-Only /* cell.IsEditing = true; * track.SetValueToField(field, wm.Text); * cell.IsEditing = false;*/ } }
private void RatingCell_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DataGridRow row = VisualTreeExtensions.FindParent <DataGridRow>((DependencyObject)e.OriginalSource); DataGridCell cell = VisualTreeExtensions.FindParent <DataGridCell>((DependencyObject)e.OriginalSource); DataGridColumn column = cell.Column; RatingUserControl ratingUserControl = sender as RatingUserControl; MyMusicListItem musicItem = row.DataContext as MyMusicListItem; dataGrid.CommitEdit(DataGridEditingUnit.Row, true); if (this.dataGrid.SelectedItems.Count > 1) { WpfMessageBoxResult result = WPFMessageBox.Show(Window.GetWindow(this), StringTable.MultiTagEdit, StringTable.MultiTagEditWarning, "/Big3.Hitbase.SharedResources;component/Images/RenameLarge.png", WpfMessageBoxButtons.YesNo, "MultiTagEdit", false); if (result == WpfMessageBoxResult.Yes) { Field field = (Field)column.GetValue(DataGridExtensions.FieldProperty); int columnIndex = column.DisplayIndex - 1; musicItem.Items[columnIndex] = ratingUserControl.Rating; PerformMultiEdit(musicItem, field, columnIndex); } } else { Field field = (Field)column.GetValue(DataGridExtensions.FieldProperty); musicItem.Items[column.DisplayIndex - 1] = ratingUserControl.Rating; EditTrackField(column.DisplayIndex - 1, field, musicItem); } }
/// <summary> /// Presents the user with a dialog box for managing the columns. /// </summary> /// <param name="sender">The object that originated the event.</param> /// <param name="e">The event data.</param> void OnMore(Object sender, ExecutedRoutedEventArgs e) { // This will extract the context menu that generated this event from the generic arguments. ContextMenu contextMenu = sender as ContextMenu; // From the context menu, we need the target that orignated the event and from that we can finally get the column set on which we want to operate. ColumnViewColumnHeader columnViewColumnHeader = contextMenu.PlacementTarget as ColumnViewColumnHeader; ListView listView = VisualTreeExtensions.FindAncestor <ListView>(columnViewColumnHeader); ColumnView columnView = listView.View as ColumnView; // This dialog box is used to add, remove, move or resize the columns in the view. It can't operate directly on the set of columns because those are // linked dynamically to the view, so we'll create a shallow clone of the values. ColumnViewChooseDetail columnViewChooseDetail = new ColumnViewChooseDetail(); foreach (ColumnViewColumn columnViewColumn in columnView.Columns) { columnViewChooseDetail.ListBox.Items.Add(new ColumnDescription(columnViewColumn)); } // Present the user with the chance to manage the columns. If the OK key is hit then copy the values out of the shallow copy and into the live column // set where they'll update the view. if (columnViewChooseDetail.ShowDialog() == true) { foreach (ColumnDescription columnDescription in columnViewChooseDetail.ListBox.Items) { ColumnViewColumn columnViewColumn = columnDescription.Column; columnViewColumn.IsVisible = columnDescription.IsVisible; columnViewColumn.Width = columnDescription.Width; } } }
/// <summary> /// Called when the parent of the visual MenuItem changes. /// </summary> /// <param name="oldParent">Old value of the parent of the visual, or null if the visual did not have a parent.</param> protected override void OnVisualParentChanged(DependencyObject oldParent) { // This control will automatically bind to properties on a TreeFrame. However, the control may be moved from one parent to the next, such as when it // moves from the overflow panel back to the main tool bar. To handle the fact that the visual tree can change, this method is need to disconnect // the control when it is in limbo and reconnect it when it's found a new home. ExplorerFrame explorerFrame = VisualTreeExtensions.FindAncestor <ExplorerFrame>(this); if (explorerFrame == null) { // Disconnect the bindings to the ancestor TreeFrame when the control is floating without a TreeFrame ancestor. BindingOperations.ClearBinding(this, ViewButton.ViewValueProperty); BindingOperations.ClearBinding(this, ViewButton.ViewModeProperty); } else { // This will automatically connect the Value property to the ancestor TreeView when it's found a new home. Binding viewValueBinding = new Binding(); viewValueBinding.Path = new PropertyPath("ViewValue"); viewValueBinding.Source = explorerFrame; viewValueBinding.Mode = BindingMode.TwoWay; BindingOperations.SetBinding(this, ViewButton.ViewValueProperty, viewValueBinding); } // Allow the base class to handle the rest of the event. base.OnVisualParentChanged(oldParent); }
public void ShouldReturnOnlySameElement() { var elem = new Grid(); var elems = VisualTreeExtensions.GetAscendantsAndSelf(elem); Assert.AreEqual(1, elems.Count(), "Должен вернуться только один элемент."); Assert.AreEqual(elem, elems.FirstOrDefault(), "Должен вернуться только тот же элемент."); }
private bool PrepareElement(UIElement element) { if (VisualTreeExtensions.GetPlaneProjection(element, true) == null) { return(false); } return(true); }
private void SelectRow(DataGridRow row) { RootTreeGrid.SelectedItem = row; row.IsSelected = true; var presenter = VisualTreeExtensions.FindFirstVisualChildOfType <DataGridCellsPresenter>(row); var cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell; cell.Focus(); }
private void ItemContainer_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { ListBoxItem item = VisualTreeExtensions.FindParent <ListBoxItem>(e.OriginalSource as DependencyObject); if (item != null) { PictureSearchItem pictureSearchItem = item.DataContext as PictureSearchItem; LoadOriginalImage(pictureSearchItem); } }
public HelpView() { InitializeComponent(); if (!DesignMode.DesignModeEnabled) { HelpTextControl.Style = VisualTreeExtensions.LoadFromAppResource <Style>("HelpText_{culture}") ?? VisualTreeExtensions.LoadFromAppResource <Style>("HelpText_en-US"); } }
/// <summary> /// Event handler for the <see cref="PreviewMouseLeftButtonDown"/> event /// </summary> /// <remarks> /// Occurs when the left mouse button is pressed while the mouse pointer is over this element. /// </remarks> /// <param name="sender">the sender of the event</param> /// <param name="e">the <see cref="MouseButtonEventArgs"/> associated to the event</param> private void PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount != 1 || VisualTreeExtensions.HitTestScrollBar(sender, e) || VisualTreeExtensions.HitTestGridColumnHeader(sender, e)) { this.dragInfo = null; return; } this.dragInfo = new DragInfo(sender, e); }
private void AddToPlaylistPlayLast(object sender, System.Windows.RoutedEventArgs e) { DataGridRow dataGridRow = VisualTreeExtensions.FindParent <DataGridRow>((System.Windows.DependencyObject)sender); MyMusicListItem myMusicListItem = dataGridRow.DataContext as MyMusicListItem; if (myMusicListItem != null) { string soundFile = DataBase.GetSoundfileByTrackId(myMusicListItem.ID); AddTracksFromSearchResult(soundFile, AddTracksToPlaylistType.End); } }
internal static void ForEachParentAndNode <TNodeType>(DependencyObject node, Func <TNodeType, bool> callback) where TNodeType : class { foreach (DependencyObject dependencyObject in VisualTreeExtensions.GetVisualAncestorsAndSelf(node)) { TNodeType nodeType = dependencyObject as TNodeType; if ((object)nodeType != null && !callback(nodeType)) { break; } } }
private async void VisualHeader_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { var listView = App._shell.GetChildOfType <ListViewBase>(); if (listView == null) { return; } await VisualTreeExtensions.ScrollToIndex(listView, 0); }
public void TreeView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { // 注意,这里的sender是TreeView // 我们需要从e.OriginalSource拿到TreeViewItem var item = VisualTreeExtensions.GetTemplatedAncestor <TreeViewItem>(e.OriginalSource as FrameworkElement); if (item != null) { item.IsSelected = true; } }
private void AddToPlaylistPreListen(object sender, System.Windows.RoutedEventArgs e) { DataGridRow dataGridRow = VisualTreeExtensions.FindParent <DataGridRow>((System.Windows.DependencyObject)sender); MyMusicListItem myMusicListItem = dataGridRow.DataContext as MyMusicListItem; if (myMusicListItem != null) { Track track = DataBase.GetTrackById(myMusicListItem.ID); HitbaseCommands.PreListenTrack.Execute(track, this); } }