public static void OnEnableSelectionpChanged(DependencyObject s, DependencyPropertyChangedEventArgs e) { if (s is ListView) { ListView control = s as ListView; var OnScrollChange = (RoutedEventHandler) delegate(object sender, RoutedEventArgs args) { ItemsPresenter ip = UITools.FindVisualChild <ItemsPresenter>(sender as ListView); ScrollContentPresenter p = UITools.FindAncestor <ScrollContentPresenter>(ip); if (GetIsDragging(p) && Mouse.LeftButton == MouseButtonState.Pressed) { UpdatePosition(p, true); } }; var OnMouseDown = (RoutedEventHandler) delegate(object sender, RoutedEventArgs args) { ClearSelection(sender as ListView); }; var OnSizeChanged = (RoutedEventHandler) delegate(object sender, RoutedEventArgs args) { ItemsPresenter ip = UITools.FindVisualChild <ItemsPresenter>(sender as ListView); ScrollContentPresenter p = UITools.FindAncestor <ScrollContentPresenter>(ip); EndDragging(p); }; Action unloadAdorner = () => { ScrollContentPresenter p = GetLastScrollContentPresenter(control); if (p != null) { SelectionAdorner _adorner = GetSelectionAdorner(p); if (AdornerLayer.GetAdornerLayer(p) != null) { AdornerLayer.GetAdornerLayer(p).Remove(_adorner); } control.MouseUp -= new MouseButtonEventHandler(OnMouseUp); control.MouseMove -= new MouseEventHandler(OnMouseMove); _adorner.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown); _adorner.MouseMove -= new MouseEventHandler(OnMouseMove); _adorner.MouseUp -= new MouseButtonEventHandler(OnMouseUp); control.RemoveHandler(ListView.SizeChangedEvent, OnSizeChanged); SetSelectionAdorner(p, null); } }; Action attachAdorner = () => { unloadAdorner(); ItemsPresenter ip = UITools.FindVisualChild <ItemsPresenter>(control); ScrollContentPresenter p = UITools.FindAncestor <ScrollContentPresenter>(ip); if (p != null) { SelectionAdorner _adorner = new SelectionAdorner(p); SetSelectionAdorner(p, _adorner); AdornerLayer.GetAdornerLayer(p).Add(_adorner); control.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown); control.MouseUp += new MouseButtonEventHandler(OnMouseUp); control.MouseMove += new MouseEventHandler(OnMouseMove); _adorner.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown); _adorner.MouseMove += new MouseEventHandler(OnMouseMove); _adorner.MouseUp += new MouseButtonEventHandler(OnMouseUp); control.AddHandler(ListView.SizeChangedEvent, OnSizeChanged); SetLastScrollContentPresenter(control, p); } }; if ((bool)e.NewValue == true) { if (control.IsLoaded) { attachAdorner(); } else { control.Loaded += delegate { attachAdorner(); } }; control.AddHandler(ScrollViewer.ScrollChangedEvent, OnScrollChange); control.AddHandler(ListView.MouseDownEvent, OnMouseDown); //Monitor view change, and reattach handlers. DependencyPropertyDescriptor viewDescriptor = DependencyPropertyDescriptor.FromProperty(ListView.ViewProperty, typeof(ListView)); viewDescriptor.AddValueChanged (control, delegate { control.Dispatcher.BeginInvoke(DispatcherPriority.Input, attachAdorner); }); } else //If EnableSelection = False { unloadAdorner(); control.RemoveHandler(ScrollViewer.ScrollChangedEvent, OnScrollChange); control.RemoveHandler(ListView.MouseDownEvent, OnMouseDown); SetSelectionAdorner(control, null); } } }
public override void OnApplyTemplate() { base.OnApplyTemplate(); _categoryRowItemPresenter = this.GetTemplateChild("CategoryRowItemPresenter") as ItemsPresenter; }
public override void OnApplyTemplate() { base.OnApplyTemplate(); _itemsPresenter = (ItemsPresenter)GetTemplateChild("WizardItemPresenter"); UpdateDesignModeDisplay(); }
/// <summary> /// When overridden in a derived class, is invoked whenever application /// code or internal processes call ApplyTemplate /// </summary> public override void OnApplyTemplate() { presenter = GetTemplateChild("PART_ItemsPresenter") as ItemsPresenter; }
/// <summary> /// Recursively search for an item in this subtree. /// </summary> /// <param name="container"> /// The parent ItemsControl. This can be a TreeView or a TreeViewItem. /// </param> /// <param name="item"> /// The item to search for. /// </param> /// <returns> /// The TreeViewItem that contains the specified item. /// </returns> private static TreeViewItem GetTreeViewItem(ItemsControl container, object item) { if (container != null) { if (container.DataContext == item) { return(container as TreeViewItem); } // Expand the current container if (container is TreeViewItem && !((TreeViewItem)container).IsExpanded) { container.SetValue(TreeViewItem.IsExpandedProperty, true); } // Try to generate the ItemsPresenter and the ItemsPanel. // by calling ApplyTemplate. Note that in the // virtualizing case even if the item is marked // expanded we still need to do this step in order to // regenerate the visuals because they may have been virtualized away. container.ApplyTemplate(); ItemsPresenter itemsPresenter = (ItemsPresenter)container.Template.FindName("ItemsHost", container); if (itemsPresenter != null) { itemsPresenter.ApplyTemplate(); } else { // The Tree template has not named the ItemsPresenter, // so walk the descendents and find the child. itemsPresenter = FindVisualChild <ItemsPresenter>(container); if (itemsPresenter == null) { container.UpdateLayout(); itemsPresenter = FindVisualChild <ItemsPresenter>(container); } } Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0); // Ensure that the generator for this panel has been created. UIElementCollection children = itemsHostPanel.Children; MyVirtualizingStackPanel virtualizingPanel = itemsHostPanel as MyVirtualizingStackPanel; for (int i = 0, count = container.Items.Count; i < count; i++) { TreeViewItem subContainer; if (virtualizingPanel != null) { // Bring the item into view so // that the container will be generated. virtualizingPanel.BringIntoView(i); subContainer = (TreeViewItem)container.ItemContainerGenerator. ContainerFromIndex(i); } else { subContainer = (TreeViewItem)container.ItemContainerGenerator. ContainerFromIndex(i); // Bring the item into view to maintain the // same behavior as with a virtualizing panel. subContainer.BringIntoView(); } if (subContainer != null) { // Search the next level for the object. TreeViewItem resultContainer = GetTreeViewItem(subContainer, item); if (resultContainer != null) { return(resultContainer); } else { // The object is not under this TreeViewItem // so collapse it. subContainer.IsExpanded = false; } } } } return(null); }
/// <summary> /// Invoked whenever application code or internal processes (such as a rebuilding /// layout pass) call <see cref="OnApplyTemplate"/>. In simplest terms, this means the method /// is called just before a UI element displays in an application. Override this /// method to influence the default post-template logic of a class. /// </summary> protected override void OnApplyTemplate() { if (_scroller != null) { _scroller.Loaded -= Scroller_Loaded; _scroller.DirectManipulationCompleted -= Scroller_DirectManipulationCompleted; _scroller.DirectManipulationStarted -= Scroller_DirectManipulationStarted; } if (_refreshIndicatorBorder != null) { _refreshIndicatorBorder.SizeChanged -= RefreshIndicatorBorder_SizeChanged; } if (_root != null) { _root.ManipulationStarted -= Scroller_ManipulationStarted; _root.ManipulationCompleted -= Scroller_ManipulationCompleted; } _root = GetTemplateChild(PartRoot) as Border; _scroller = GetTemplateChild(PartScroller) as ScrollViewer; _scrollerContent = GetTemplateChild(PartScrollerContent) as ItemsPresenter; _refreshIndicatorBorder = GetTemplateChild(PartRefreshIndicatorBorder) as Border; _refreshIndicatorTransform = GetTemplateChild(PartIndicatorTransform) as CompositeTransform; _defaultIndicatorContent = GetTemplateChild(PartDefaultIndicatorContent) as TextBlock; _pullAndReleaseIndicatorContent = GetTemplateChild(PullAndReleaseIndicatorContent) as ContentPresenter; if (_root != null && _scroller != null && _scrollerContent != null && _refreshIndicatorBorder != null && _refreshIndicatorTransform != null && (_defaultIndicatorContent != null || _pullAndReleaseIndicatorContent != null)) { _scroller.Loaded += Scroller_Loaded; if (IsPullToRefreshWithMouseEnabled) { _root.ManipulationMode = ManipulationModes.TranslateY; _root.ManipulationStarted += Scroller_ManipulationStarted; _root.ManipulationCompleted += Scroller_ManipulationCompleted; } _scroller.DirectManipulationCompleted += Scroller_DirectManipulationCompleted; _scroller.DirectManipulationStarted += Scroller_DirectManipulationStarted; if (_defaultIndicatorContent != null) { _defaultIndicatorContent.Visibility = RefreshIndicatorContent == null ? Visibility.Visible : Visibility.Collapsed; } if (_pullAndReleaseIndicatorContent != null) { _pullAndReleaseIndicatorContent.Visibility = RefreshIndicatorContent == null ? Visibility.Visible : Visibility.Collapsed; } _refreshIndicatorBorder.SizeChanged += RefreshIndicatorBorder_SizeChanged; _overscrollMultiplier = OverscrollLimit * 8; } base.OnApplyTemplate(); }
/// <summary> /// Selects the UI element in the specified <i>control</i> based on the corresponding <i>info</i>. /// </summary> /// <typeparam name="T">The type of item to match.</typeparam> /// <param name="container">The <see cref="ItemsControl"/> in which to dumpster dive.</param> /// <param name="info">Control parameters used in the search.</param> private static void SelectContainerFromItem <T>(this ItemsControl container, SelectInfo <T> selectInfo) { var currentItem = selectInfo.Items.First(); if (container.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) { // If the item containers haven't been generated yet, attach an event // and wait for the status to change. EventHandler selectWhenReadyMethod = null; selectWhenReadyMethod = (ds, de) => { if (container.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { // Stop listening for status changes on this container container.ItemContainerGenerator.StatusChanged -= selectWhenReadyMethod; // Search the container for the item chain SelectContainerFromItem(container, selectInfo); } }; container.ItemContainerGenerator.StatusChanged += selectWhenReadyMethod; return; } Debug.Assert(container.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated); // Compare each item in the container and look for the next item // in the chain. foreach (object item in container.Items) { var convertedItem = (T)item; // Compare the converted item with the item in the chain if ((selectInfo.CompareMethod != null) && selectInfo.CompareMethod(convertedItem, currentItem)) { // Since the TreeViewItems are in a virtualized panel, the item to be selected may not be realized, // need to ensure it is brought into view, so it can be selected. ItemsPresenter itemsPresenter = FindVisualChild <ItemsPresenter>(container); if (itemsPresenter != null) { VirtualizingStackPanel virtualizingPanel = (VirtualizingStackPanel)VisualTreeHelper.GetChild(itemsPresenter, 0); if (virtualizingPanel != null) { virtualizingPanel.BringIndexIntoViewPublic(container.Items.IndexOf(currentItem)); } } var containerParent = (ItemsControl)container.ItemContainerGenerator.ContainerFromItem(item); Debug.Assert(containerParent != null, "Failed to find the parent container for the selected item."); // Replace with the remaining items in the chain selectInfo.Items = selectInfo.Items.Skip(1); // If no items are left in the chain, then we're finished if (selectInfo.Items.Count() == 0) { // Select the last item if (selectInfo.SelectItem != null) { Action action = new Action(() => { selectInfo.SelectItem(containerParent, selectInfo); }); // Here we dispatch the select action so the TreeViewItem is focused // and scrolled into view correctly. container.Dispatcher.BeginInvoke(action, DispatcherPriority.Render); } } else { // Request more items and continue the search if (selectInfo.NeedMoreItems != null) { selectInfo.NeedMoreItems(containerParent, selectInfo); SelectContainerFromItem(containerParent, selectInfo); } } break; } } }
public override void OnApplyTemplate() { base.OnApplyTemplate(); _itemsPresenter = (ItemsPresenter)GetTemplateChild("ItemsPresenter"); }
protected override Size MeasureOverride(Size availableSize) { Debug.WriteLine("GanttRow.MeasureOverride()"); ItemsPresenter.Measure(availableSize); return(base.MeasureOverride(availableSize)); }
private void Rebuild() { if (this.editingProperty == null) { this.BrushSubtypeEditor = (BrushSubtypeEditor)null; } else { if (!this.editingProperty.Associated) { return; } this.oldNichedState = this.editingProperty.IsMixedValue; this.editingResource = false; bool flag = this.brushSubtypeEditor is BrushEditor.NullBrushEditor; if (this.editingProperty.IsResource) { this.editingResource = true; this.editingProperty.SceneNodeObjectSet.InvalidateLocalResourcesCache(); this.BrushSubtypeEditor = (BrushSubtypeEditor)null; this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Delegate)(o => { if (this.editingProperty != null && this.ResourceList.IsLoaded && this.Parent != null) { this.ResourceList.ApplyTemplate(); ItemsControl itemsControl = (ItemsControl)this.ResourceList.Template.FindName("ResourcesControl", (FrameworkElement)this.ResourceList); itemsControl.ApplyTemplate(); ItemsPresenter itemsPresenter = (ItemsPresenter)itemsControl.Template.FindName("ResourcesItemsPresenter", (FrameworkElement)itemsControl); itemsPresenter.ApplyTemplate(); WorkaroundVirtualizingStackPanel virtualizingStackPanel = (WorkaroundVirtualizingStackPanel)itemsControl.ItemsPanel.FindName("VirtualizingStackPanel", (FrameworkElement)itemsPresenter); int index = -1; if (this.editingProperty.SelectedLocalResourceModel != null) { this.editingProperty.SelectedLocalResourceModel.Parent.IsExpanded = true; index = itemsControl.Items.IndexOf((object)this.editingProperty.SelectedLocalResourceModel); } else if (this.editingProperty.SelectedSystemResourceModel != null) { this.editingProperty.SelectedSystemResourceModel.Parent.IsExpanded = true; index = itemsControl.Items.IndexOf((object)this.editingProperty.SelectedSystemResourceModel); } if (index >= 0) { virtualizingStackPanel.BringIndexIntoViewWorkaround(index); } } return((object)null); }), (object)null); } else if (this.editingProperty.IsMixedValue) { this.BrushSubtypeEditor = (BrushSubtypeEditor)null; } else { ITypeId typeId = (ITypeId)this.editingProperty.ComputedValueTypeId; if (typeId != null) { if (typeId.Equals((object)PlatformTypes.SolidColorBrush) && !(this.BrushSubtypeEditor is SolidColorBrushEditor)) { this.BrushSubtypeEditor = (BrushSubtypeEditor) new SolidColorBrushEditor(this, this.editingProperty); } else if (PlatformTypes.GradientBrush.IsAssignableFrom(typeId)) { if (this.BrushSubtypeEditor == null || !typeId.Equals((object)this.BrushSubtypeEditor.Category.Type)) { this.BrushSubtypeEditor = (BrushSubtypeEditor) new GradientBrushEditor(this, typeId, this.editingProperty); } } else if (PlatformTypes.TileBrush.IsAssignableFrom(typeId) && (this.BrushSubtypeEditor == null || !typeId.Equals((object)this.BrushSubtypeEditor.Category.Type))) { this.BrushSubtypeEditor = (BrushSubtypeEditor) new TileBrushEditor(this, typeId, this.editingProperty); } if (this.BrushSubtypeEditor != null) { BrushCategory.SetLastUsed(this.BrushSubtypeEditor.Category, this.editingProperty.GetValue()); } } else { this.BrushSubtypeEditor = (BrushSubtypeEditor) new BrushEditor.NullBrushEditor(); } } if (!(this.brushSubtypeEditor is BrushEditor.NullBrushEditor) && flag) { this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Delegate)(o => { this.BringIntoView(); return((object)null); }), (object)null); } this.OnEditingTypeChange(); } }
public void JumpBackAPanoramaItemAnimated() { Panorama pan = this.mainPanorama; // ActualWidth 480 FrameworkElement grid1 = VisualTreeHelper.GetChild(pan, 0) as FrameworkElement; FrameworkElement ptl1 = VisualTreeHelper.GetChild(grid1, 1) as FrameworkElement; FrameworkElement sp2 = VisualTreeHelper.GetChild(ptl1, 0) as FrameworkElement; FrameworkElement cp2 = VisualTreeHelper.GetChild(sp2, 1) as FrameworkElement; FrameworkElement image1 = VisualTreeHelper.GetChild(cp2, 0) as FrameworkElement; FrameworkElement rect4 = VisualTreeHelper.GetChild(sp2, 2) as FrameworkElement; FrameworkElement pl = VisualTreeHelper.GetChild(grid1, 2) as FrameworkElement; FrameworkElement sp3 = VisualTreeHelper.GetChild(pl, 0) as FrameworkElement; FrameworkElement rect5 = VisualTreeHelper.GetChild(sp3, 0) as FrameworkElement; FrameworkElement cp4 = VisualTreeHelper.GetChild(sp3, 1) as FrameworkElement; ItemsPresenter ip1 = VisualTreeHelper.GetChild(cp4, 0) as ItemsPresenter; PanoramaPanel pp = VisualTreeHelper.GetChild(ip1, 0) as PanoramaPanel; PanoramaItem pi1 = VisualTreeHelper.GetChild(pp, 0) as PanoramaItem; int numPanelsToJump = 4; double panItemWidth = pi1.ActualWidth; //double relfinalPanTitleTranslate = - numPanelsToJump * 160; //double titleJump = -(numPanelsToJump * panItemWidth); //double finalPanTitleTranslate = numPanelsToJump * panItemWidth + relfinalPanTitleTranslate; double relfinalPanTitleTranslate = -numPanelsToJump * 160; //double titleJump = -(image1.ActualWidth + 348); double titleJump = -(ptl1.ActualWidth - rect4.ActualWidth); double finalPanTitleTranslate = -titleJump + relfinalPanTitleTranslate; //rect4.Width = 0; int lastInd = pp.Children.Count - 1; int currInd = 0; int numPanoramaItems = pp.Children.Count; double t = 550; IEasingFunction easing = new CubicEase() { EasingMode = EasingMode.EaseInOut, }; UIElement pi = pp.Children[lastInd]; pp.Children.Remove(pi); pp.Children.Insert(0, pi); // This jumps forward and messes up the title position pan.SetValue(Panorama.SelectedItemProperty, pp.Children[(currInd + 1) % numPanoramaItems] as PanoramaItem); ptl1.RenderTransform = new TranslateTransform(); // Keep a reference to the RenderTransform on the StackPanel since this is used for the // inbuilt swipe navigation animation Transform spTransform = sp2.RenderTransform; // Set this offset since the home PanoramaItem is now the second in the list and the title // automatically jumps into the second PanoramaItem position sp2.RenderTransform = new TranslateTransform() { X = 0 }; pl.RenderTransform = new TranslateTransform() { X = 0 }; this.LayoutRoot.IsHitTestVisible = false; // Any smaller and it chops off the second instance of the title content this.LayoutRoot.Width = 3 * App.VM.ScreenWidth; // Need to set panorama to screen size and align to the left to remain onscreen pan.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; pan.Width = App.VM.ScreenWidth; Storyboard sb = new Storyboard(); // Animate title using the StackPanel DoubleAnimation animTitle = new DoubleAnimation() { From = 0, To = finalPanTitleTranslate, Duration = TimeSpan.FromMilliseconds(t), EasingFunction = easing, }; sb.Children.Add(animTitle); Storyboard.SetTarget(animTitle, sp2.RenderTransform); Storyboard.SetTargetProperty(animTitle, new PropertyPath(TranslateTransform.XProperty)); // Jump the entire panning layer back before animating the title so the second instance of ContentPresenter is shown // allowing the first instance to anmate in from the left DoubleAnimationUsingKeyFrames jumpTitleAnim = new DoubleAnimationUsingKeyFrames(); jumpTitleAnim.KeyFrames.Add(new DiscreteDoubleKeyFrame() { KeyTime = TimeSpan.FromMilliseconds(0), Value = titleJump, }); sb.Children.Add(jumpTitleAnim); Storyboard.SetTarget(jumpTitleAnim, ptl1.RenderTransform); Storyboard.SetTargetProperty(jumpTitleAnim, new PropertyPath(TranslateTransform.XProperty)); // Animate the main Panorama items DoubleAnimation animMain = new DoubleAnimation() { From = 0, To = panItemWidth, Duration = TimeSpan.FromMilliseconds(t), EasingFunction = easing, }; sb.Children.Add(animMain); Storyboard.SetTarget(animMain, pl.RenderTransform); Storyboard.SetTargetProperty(animMain, new PropertyPath(TranslateTransform.XProperty)); sb.Begin(); sb.Completed += (obj, args) => { pan.Width = App.VM.ScreenWidth; this.LayoutRoot.Width = App.VM.ScreenWidth; // Append PanoramaItem back to the end of the ItemsPresenter pp.Children.Remove(pi); pp.Children.Add(pi); (pl.RenderTransform as TranslateTransform).X = 0; (ptl1.RenderTransform as TranslateTransform).X = 0; // Reset (pan.Items[(currInd + 1) & numPanoramaItems] as PanoramaItem).Visibility = Visibility.Collapsed; pan.SetValue(Panorama.SelectedItemProperty, pan.Items[lastInd]); pan.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); (pan.Items[(currInd + 1) & numPanoramaItems] as PanoramaItem).Visibility = Visibility.Visible; // Restore the StackPanel animation necessary for normal animation sp2.RenderTransform = spTransform; this.LayoutRoot.IsHitTestVisible = true; }; }
override void OnApplyTemplate() { base.OnApplyTemplate(); _suppressAnimations = false; _itemsList = GetTemplateChild(ItemsListName) as ItemsPresenter; #if WINDOWS_PHONE _itemsList.CacheMode = new BitmapCache(); #endif _translate = GetTemplateChild(SlidingTransformName) as TranslateTransform; }
// this method is based on and modified from: // https://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-find-a-treeviewitem-in-a-treeview /// <summary> /// Recursively search for an item in this subtree. /// </summary> /// <param name="container"> /// The parent ItemsControl. This can be a TreeView or a TreeViewItem. /// </param> /// <param name="item"> /// The item to search for. /// </param> /// <returns> /// The TreeViewItem that contains the specified item. /// </returns> private static TreeViewItem GetTreeViewItem(ItemsControl container, object item, object selectedItem, SearchDirection dir, int depth) { if (container != null) { if (container.DataContext == item) { return(container as TreeViewItem); } else if (depth <= 0) { return(null); } // Expand the current container if (container is TreeViewItem && !((TreeViewItem)container).IsExpanded) { container.SetValue(TreeViewItem.IsExpandedProperty, true); } // Try to generate the ItemsPresenter and the ItemsPanel. // by calling ApplyTemplate. Note that in the // virtualizing case even if the item is marked // expanded we still need to do this step in order to // regenerate the visuals because they may have been virtualized away. container.ApplyTemplate(); ItemsPresenter itemsPresenter = (ItemsPresenter)container.Template.FindName("ItemsHost", container); if (itemsPresenter != null) { itemsPresenter.ApplyTemplate(); } else { // The Tree template has not named the ItemsPresenter, // so walk the descendants and find the child. itemsPresenter = FindVisualChild <ItemsPresenter>(container); if (itemsPresenter == null) { container.UpdateLayout(); itemsPresenter = FindVisualChild <ItemsPresenter>(container); } } Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0); // Ensure that the generator for this panel has been created. _ = itemsHostPanel.Children; int startIndex = -1; if (selectedItem != null) { startIndex = IndexForItem(container.ItemContainerGenerator, selectedItem); } int count = container.Items.Count; int inc = dir == SearchDirection.Down ? 1 : -1; int idx = startIndex > -1 ? startIndex : dir == SearchDirection.Down ? 0 : count - 1; for (; idx < count && idx >= 0; idx += inc) { TreeViewItem subContainer; if (itemsHostPanel is MyVirtualizingStackPanel virtualizingPanel) { // Bring the item into view so // that the container will be generated. virtualizingPanel.BringIntoView(idx); subContainer = (TreeViewItem)container.ItemContainerGenerator. ContainerFromIndex(idx); } else { subContainer = (TreeViewItem)container.ItemContainerGenerator. ContainerFromIndex(idx); if (subContainer != null) { // Bring the item into view to maintain the // same behavior as with a virtualizing panel. subContainer.BringIntoView(); } } if (subContainer != null) { // Search the next level for the object. TreeViewItem resultContainer = GetTreeViewItem(subContainer, item, selectedItem, dir, depth - 1); if (resultContainer != null) { return(resultContainer); } else { // The object is not under this TreeViewItem // so collapse it. subContainer.IsExpanded = false; } } } } return(null); }
public void ItemsControlTemplatesTest() { string text = @" <ItemsControl xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <DockPanel/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.Template> <ControlTemplate> <Grid> <TextBlock Text='Header'/> <ItemsPresenter ItemContainerGenerator='{TemplateBinding ItemsControl.ItemContainerGenerator}' Template='{TemplateBinding ItemsControl.ItemsPanel}'/> </Grid> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemContainerStyle> <Style> <Setter Property='DockPanel.Dock' Value='Bottom'/> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text='{Binding}'/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>"; ItemsControl itemsControl = XamlLoader.Load(XamlParser.Parse(text)) as ItemsControl; itemsControl.Items.Add("item1"); itemsControl.Items.Add("item2"); itemsControl.Items.Add("item3"); Grid grid = itemsControl.VisualChildren.FirstOrDefault() as Grid; Assert.IsNotNull(grid); Assert.AreEqual(2, grid.Children.Count); TextBlock textBlock = grid.Children[0] as TextBlock; ItemsPresenter itemsPresenter = grid.Children[1] as ItemsPresenter; Assert.IsNotNull(textBlock); Assert.IsNotNull(itemsPresenter); Assert.AreEqual("Header", textBlock.Text); DockPanel dockPanel = itemsPresenter.VisualChildren.FirstOrDefault() as DockPanel; Assert.IsNotNull(dockPanel); Assert.AreEqual(3, dockPanel.Children.Count); ContentPresenter presenter1 = dockPanel.Children[0] as ContentPresenter; ContentPresenter presenter2 = dockPanel.Children[1] as ContentPresenter; ContentPresenter presenter3 = dockPanel.Children[2] as ContentPresenter; Assert.IsNotNull(presenter1); Assert.IsNotNull(presenter2); Assert.IsNotNull(presenter3); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter1)); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter2)); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter3)); TextBlock textBlock1 = presenter1.VisualChildren.FirstOrDefault() as TextBlock; Assert.IsNotNull(textBlock1); Assert.AreEqual("item1", textBlock1.Text); itemsControl.Items[0] = "item4"; Assert.IsFalse(presenter1.VisualChildren.Any()); Assert.IsNull(textBlock1.Text); ContentPresenter presenter4 = dockPanel.Children[0] as ContentPresenter; Assert.AreNotEqual(presenter1, presenter4); TextBlock textBlock4 = presenter4.VisualChildren.FirstOrDefault() as TextBlock; Assert.AreEqual("item4", textBlock4.Text); }