Пример #1
0
 public void Items_Not_Should_Be_Readonly_When_ItemsSource_Nulled()
 {
     ItemsControl target = new ItemsControl();
     target.ItemsSource = new int[1];
     target.ItemsSource = null;
     target.Items.Add(1);
 }
Пример #2
0
        public static void Main()
        {
            var mainViewModel = new MainViewModel();

            var button = new Button()
            {
                Command = mainViewModel.PostCommand,
                TextContent = "Post"
            };

            var headerInput = new TextInput();
            headerInput.PlaceHolder = "Header";
            SimpleBinding.Create(mainViewModel, "HeaderInput", headerInput, "Value");

            var contentInput = new TextInput();
            contentInput.PlaceHolder = "Content";
            SimpleBinding.Create(mainViewModel, "ContentInput", contentInput, "Value");

            var list = new ItemsControl<Post>(new VBox())
            {
                // "postItemTemplate" is a reference to an element defined in MainPage.html
                ItemElementFactory = new TemplateElementFactory<Post>("postItemTemplate")
            };
            SimpleBinding.Create(list, "ItemsSource", mainViewModel, "Posts");

            var box = new VBox
            {
                Content = { headerInput, contentInput, button, list }
            };

            Element.GetById("target").AppendChild(box);
        }
Пример #3
0
 private void Awake()
 {
     m_rectTransform = GetComponent<RectTransform>();
     SiblingGraphics.SetActive(true);
     m_parentCanvas = GetComponentInParent<Canvas>();
     m_itemsControl = GetComponentInParent<ItemsControl>();
     AwakeOverride();
 }
 public virtual void GetItemsHostForItemsControl()
 {
     ItemsControl control = new ItemsControl { ItemsSource = new[] { 1, 2, 3, 4 } };
     Panel host = null;
     TestAsync(
         control,
         () => host = control.GetItemsHost(),
         () => Assert.IsNotNull(host, "ItemsHost not found!"));
 }
Пример #5
0
        public void ItemsSource_Set_Assigns_Items()
        {
            ItemsControl target = new ItemsControl();
            int[] collection = new int[1];

            target.ItemsSource = collection;

            Assert.AreSame(collection, target.Items.SourceCollection);
        }
Пример #6
0
        public void Items_Should_Not_Change_Instance_When_ItemsSource_Set()
        {
            ItemsControl target = new ItemsControl();
            ItemCollection before = target.Items;

            target.ItemsSource = new int[1];

            Assert.AreSame(before, target.Items);
        }
Пример #7
0
        public void ItemsSource_Null_Unassigns_Items()
        {
            ItemsControl target = new ItemsControl();
            int[] collection = new int[1];

            target.ItemsSource = collection;
            target.ItemsSource = null;

            Assert.AreSame(target.Items, target.Items.SourceCollection);
        }
Пример #8
0
        public void Panel_Should_Have_TemplatedParent_Set_To_ItemsControl()
        {
            var target = new ItemsControl();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();

            Assert.Equal(target, target.Presenter.Panel.TemplatedParent);
        }
Пример #9
0
        public void Adding_Control_Item_Should_Make_Control_Appear_In_LogicalChildren()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { child };
            target.ApplyTemplate();

            Assert.Equal(new[] { child }, ((ILogical)target).LogicalChildren.ToList());
        }
Пример #10
0
        public void Control_Item_Should_Have_Parent_Set()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { child };
            target.ApplyTemplate();

            Assert.Equal(target, child.Parent);
            Assert.Equal(target, ((ILogical)child).LogicalParent);
        }
Пример #11
0
        public void Control_Item_Should_Be_Logical_Child_Before_ApplyTemplate()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { child };

            Assert.Equal(child.Parent, target);
            Assert.Equal(child.GetLogicalParent(), target);
            Assert.Equal(new[] { child }, target.GetLogicalChildren());
        }
Пример #12
0
        public void Clearing_Items_Should_Clear_Child_Controls_Parent_Before_ApplyTemplate()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { child };
            target.Items = null;

            Assert.Null(child.Parent);
            Assert.Null(((ILogical)child).LogicalParent);
        }
Пример #13
0
 private async void load(ItemsControl list, Uri uri)
 {
     SyndicationClient client = new SyndicationClient();
     SyndicationFeed feed = await client.RetrieveFeedAsync(uri);
     if (feed != null)
     {
         foreach (SyndicationItem item in feed.Items)
         {
             list.Items.Add(item);
         }
     }
 }
Пример #14
0
        public void Items_Propogates_CollectionChanged_Events()
        {
            ItemsControl target = new ItemsControl();
            ObservableCollection<int> collection = new ObservableCollection<int>();
            object sender = null;

            target.ItemsSource = collection;
            ((INotifyCollectionChanged)target.Items).CollectionChanged += (s, e) => sender = s;
            collection.Add(1);

            Assert.AreSame(target.Items, sender);
        }
Пример #15
0
        public void Item_Should_Have_TemplatedParent_Set_To_Null()
        {
            var target = new ItemsControl();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();

            var item = (TextBlock)target.Presenter.Panel.GetVisualChildren().First();

            Assert.Null(item.TemplatedParent);
        }
Пример #16
0
        public void Container_Should_Have_TemplatedParent_Set_To_Null()
        {
            var target = new ItemsControl();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();
            target.Presenter.ApplyTemplate();

            var container = (ContentPresenter)target.Presenter.Panel.Children[0];

            Assert.Null(container.TemplatedParent);
        }
Пример #17
0
        public void Panel_Should_Have_TemplatedParent_Set_To_ItemsControl()
        {
            var target = new ItemsControl();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();

            var presenter = target.GetTemplateChildren().OfType<ItemsPresenter>().Single();
            var panel = target.GetTemplateChildren().OfType<StackPanel>().Single();

            Assert.Equal(target, panel.TemplatedParent);
        }
Пример #18
0
        public void Adding_String_Item_Should_Make_TextBlock_Appear_In_LogicalChildren()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();
            target.Presenter.ApplyTemplate();

            var logical = (ILogical)target;
            Assert.Equal(1, logical.LogicalChildren.Count);
            Assert.IsType<TextBlock>(logical.LogicalChildren[0]);
        }
Пример #19
0
        public void Control_Item_Should_Be_Removed_From_Logical_Children_Before_ApplyTemplate()
        {
            var target = new ItemsControl();
            var child = new Control();
            var items = new AvaloniaList<Control>(child);

            target.Template = GetTemplate();
            target.Items = items;
            items.RemoveAt(0);

            Assert.Null(child.Parent);
            Assert.Null(child.GetLogicalParent());
            Assert.Empty(target.GetLogicalChildren());
        }
Пример #20
0
        public void Item_Should_Have_TemplatedParent_Set_To_Null()
        {
            var target = new ItemsControl();

            target.Template = GetTemplate();
            target.Items = new[] { "Foo" };
            target.ApplyTemplate();

            var presenter = target.GetTemplateChildren().OfType<ItemsPresenter>().Single();
            var panel = target.GetTemplateChildren().OfType<StackPanel>().Single();
            var item = (TextBlock)panel.GetVisualChildren().First();

            Assert.Null(item.TemplatedParent);
        }
Пример #21
0
        public void Adding_Control_Item_Should_Make_Control_Appear_In_LogicalChildren()
        {
            var target = new ItemsControl();
            var child = new Control();

            target.Template = GetTemplate();
            target.Items = new[] { child };

            // Should appear both before and after applying template.
            Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren());

            target.ApplyTemplate();

            Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren());
        }
Пример #22
0
    public void Go(ref ItemsControl list, string value, KeyRoutedEventArgs args)
    {
        if (args.Key == Windows.System.VirtualKey.Enter)
        {
            try
            {
                load(list, new Uri(value));
            }
            catch
            {

            }
            list.Focus(FocusState.Keyboard);
        }
    }
Пример #23
0
        public void Changing_Items_Should_Fire_LogicalChildren_CollectionChanged()
        {
            var target = new ItemsControl();
            var child = new Control();
            var called = false;

            target.Template = GetTemplate();
            target.Items = new[] { child };
            target.ApplyTemplate();

            ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true;

            target.Items = new[] { "Foo" };

            Assert.True(called);
        }
Пример #24
0
        public void Should_Use_ItemTemplate_To_Create_Control()
        {
            var target = new ItemsControl
            {
                Template = GetTemplate(),
                ItemTemplate = new FuncDataTemplate<string>(_ => new Canvas()),
            };

            target.Items = new[] { "Foo" };
            target.ApplyTemplate();
            target.Presenter.ApplyTemplate();

            var container = (ContentPresenter)target.Presenter.Panel.Children[0];
            container.UpdateChild();

            Assert.IsType<Canvas>(container.Child);
        }
Пример #25
0
        public void Nested_TemplatedControls_Should_Be_Expanded_And_Have_Correct_TemplatedParent()
        {
            var target = new ItemsControl
            {
                Template = new ControlTemplate<ItemsControl>(ItemsControlTemplate),
                Items = new[] { "Foo", }
            };

            target.ApplyTemplate();

            var scrollViewer = target.GetVisualDescendents()
                .OfType<ScrollViewer>()
                .Single();
            var types = target.GetVisualDescendents()
                .Select(x => x.GetType())
                .ToList();
            var templatedParents = target.GetVisualDescendents()
                .OfType<IControl>()
                .Select(x => x.TemplatedParent)
                .ToList();

            Assert.Equal(
                new[]
                {
                    typeof(Border),
                    typeof(ScrollViewer),
                    typeof(ScrollContentPresenter),
                    typeof(ItemsPresenter),
                    typeof(StackPanel),
                    typeof(TextBlock),
                },
                types);

            Assert.Equal(
                new object[]
                {
                    target,
                    target,
                    scrollViewer,
                    target,
                    target,
                    null
                },
                templatedParents);
        }
Пример #26
0
        public void Adding_Items_Should_Fire_LogicalChildren_CollectionChanged()
        {
            var target = new ItemsControl();
            var items = new PerspexList<string> { "Foo" };
            var called = false;

            target.Template = GetTemplate();
            target.Items = items;
            target.ApplyTemplate();
            target.Presenter.ApplyTemplate();

            ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) =>
                called = e.Action == NotifyCollectionChangedAction.Add;

            items.Add("Bar");

            Assert.True(called);
        }
Пример #27
0
        public void Container_Child_Should_Have_LogicalParent_Set_To_Container()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var root = new Window();
                var target = new ItemsControl();

                root.Content = target;

                var templatedParent = new Button();
                target.TemplatedParent = templatedParent;
                target.Template = GetTemplate();

                target.Items = new[] { "Foo" };

                root.ApplyTemplate();
                target.ApplyTemplate();
                target.Presenter.ApplyTemplate();

                var container = (ContentPresenter)target.Presenter.Panel.Children[0];

                Assert.Equal(container, container.Child.Parent);
            }
        }
Пример #28
0
 bool ItemsControlNameComparer(ItemsControl control, string firstName, string secondName, string lastName)
 {
     return(((EnumMemberInfo)control.Items.GetItemAt(0)).Name == firstName &&
            ((EnumMemberInfo)control.Items.GetItemAt(1)).Name == secondName &&
            ((EnumMemberInfo)control.Items.GetItemAt(2)).Name == lastName);
 }
        /// <summary>
        /// Get the items and item containers of an ItemsControl.
        /// </summary>
        /// <typeparam name="TContainer">
        /// The type of the item containers.
        /// </typeparam>
        /// <param name="control">The ItemsControl.</param>
        /// <returns>The items and item containers of an ItemsControl.</returns>
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="control" /> is null.
        /// </exception>
        private static IEnumerable <KeyValuePair <object, TContainer> > GetItemsAndContainersIterator <TContainer>(ItemsControl control)
            where TContainer : DependencyObject
        {
            //Debug.Assert(control != null, "control should not be null!");

            int count = control.Items.Count;

            for (int i = 0; i < count; i++)
            {
                DependencyObject container = (DependencyObject)control.ItemContainerGenerator.ContainerFromIndex(i);
                if (container == null)
                {
                    continue;
                }

                yield return(new KeyValuePair <object, TContainer>(
                                 control.Items[i],
                                 container as TContainer));
            }
        }
Пример #30
0
 private static void SetItemsControlManager(ItemsControl itemsControl, ItemsControlManager value)
 {
     itemsControl.SetValue(ItemsControlManagerProperty, value);
 }
Пример #31
0
        protected override void OnKeyDown(KeyEventArgs e)
        {
            SharpTreeViewItem container = e.OriginalSource as SharpTreeViewItem;

            switch (e.Key)
            {
            case Key.Left:
                if (container != null && ItemsControl.ItemsControlFromItemContainer(container) == this)
                {
                    if (container.Node.IsExpanded)
                    {
                        container.Node.IsExpanded = false;
                    }
                    else if (container.Node.Parent != null)
                    {
                        this.FocusNode(container.Node.Parent);
                    }
                    e.Handled = true;
                }
                break;

            case Key.Right:
                if (container != null && ItemsControl.ItemsControlFromItemContainer(container) == this)
                {
                    if (!container.Node.IsExpanded && container.Node.ShowExpander)
                    {
                        container.Node.IsExpanded = true;
                    }
                    else if (container.Node.Children.Count > 0)
                    {
                        // jump to first child:
                        container.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
                    }
                    e.Handled = true;
                }
                break;

            case Key.Return:
            case Key.Space:
                if (container != null && Keyboard.Modifiers == ModifierKeys.None && this.SelectedItems.Count == 1 && this.SelectedItem == container.Node)
                {
                    container.Node.ActivateItem(e);
                }
                break;

            case Key.Add:
                if (container != null && ItemsControl.ItemsControlFromItemContainer(container) == this)
                {
                    container.Node.IsExpanded = true;
                    e.Handled = true;
                }
                break;

            case Key.Subtract:
                if (container != null && ItemsControl.ItemsControlFromItemContainer(container) == this)
                {
                    container.Node.IsExpanded = false;
                    e.Handled = true;
                }
                break;

            case Key.Multiply:
                if (container != null && ItemsControl.ItemsControlFromItemContainer(container) == this)
                {
                    container.Node.IsExpanded = true;
                    ExpandRecursively(container.Node);
                    e.Handled = true;
                }
                break;
            }
            if (!e.Handled)
            {
                base.OnKeyDown(e);
            }
        }
Пример #32
0
        protected override Size MeasureOverride(Size availableSize)
        {
            ItemsControl itemCtrl = ItemsControl.GetItemsOwner(this);

            if (itemCtrl.Items.Count == 0)
            {
                return(new Size());
            }

            UpdateScrollInfo(availableSize);
            // Figure out range that's visible based on layout algorithm
            int firstVisibleItemIndex, lastVisibleItemIndex;

            GetVisibleRange(out firstVisibleItemIndex, out lastVisibleItemIndex);
            // We need to access InternalChildren before the generator to work around a bug
            UIElementCollection     children  = InternalChildren;
            IItemContainerGenerator generator = ItemContainerGenerator;
            // Get the generator position of the first visible data item
            GeneratorPosition startPos = generator.GeneratorPositionFromIndex(firstVisibleItemIndex);
            // Get index where we'd insert the child for this position. If the item is realized
            // (position.Offset == 0), it's just position.Index, otherwise we have to add one to
            // insert after the corresponding child
            int childIndex = (startPos.Offset == 0) ? startPos.Index : startPos.Index + 1;

            using (generator.StartAt(startPos, GeneratorDirection.Forward, true))
            {
                for (int itemIndex = firstVisibleItemIndex;
                     itemIndex <= lastVisibleItemIndex;
                     itemIndex++, childIndex++)
                {
                    bool isNewlyRealized;
                    var  child = generator.GenerateNext(out isNewlyRealized) as UIElement;
                    if (isNewlyRealized)
                    {
                        if (childIndex >= children.Count)
                        {
                            if (child != null)
                            {
                                AddInternalChild(child);
                            }
                        }
                        else if (child != null)
                        {
                            InsertInternalChild(childIndex, child);
                        }
                        generator.PrepareItemContainer(child);
                    }
                    else
                    {
                        // The child has already been created, let's be sure it's in the right spot
                        Debug.Assert(child == children[childIndex], "Wrong child was generated");
                    }
                    // Measurements will depend on layout algorithm
                    if (child != null)
                    {
                        child.Measure(GetChildSize());
                    }
                }
            }
            // Note: this could be deferred to idle time for efficiency
            CleanUpItems(firstVisibleItemIndex, lastVisibleItemIndex);
            return(availableSize);
        }
Пример #33
0
 /// <summary>
 /// 获取数据源IEnumerable&lt;T&gt;
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="control"></param>
 /// <returns></returns>
 public static IEnumerable <T> GetItemsSource <T>(this ItemsControl control)
 => control.ItemsSource as IEnumerable <T>;
Пример #34
0
 public static bool GetInitialize(ItemsControl element) => (bool)element.GetValue(InitializeProperty);
Пример #35
0
 /// <returns>Control that contains specified TreeViewItem
 /// (either TreeView or another TreeViewItem).</returns>
 public static ItemsControl GetParent(this TreeViewItem item)
 {
     return(ItemsControl.ItemsControlFromItemContainer(item));
 }
Пример #36
0
        public static void GetItemsInViewPort(this ItemsControl list, IList <WeakReference> items)
        {
            int index;
            FrameworkElement container;
            GeneralTransform itemTransform;
            Rect             boundingBox;

            if (VisualTreeHelper.GetChildrenCount(list) == 0)
            {
                // no child yet
                return;
            }

            ScrollViewer scrollHost = VisualTreeHelper.GetChild(list, 0) as ScrollViewer;

            list.UpdateLayout();

            if (scrollHost == null)
            {
                return;
            }

            for (index = 0; index < list.Items.Count; index++)
            {
                container = (FrameworkElement)list.ItemContainerGenerator.ContainerFromIndex(index);
                if (container != null)
                {
                    itemTransform = null;
                    try
                    {
                        itemTransform = container.TransformToVisual(scrollHost);
                    }
                    catch (ArgumentException)
                    {
                        // Ignore failures when not in the visual tree
                        return;
                    }

                    boundingBox = new Rect(itemTransform.Transform(new Point()), itemTransform.Transform(new Point(container.ActualWidth, container.ActualHeight)));

                    if (boundingBox.Bottom > 0)
                    {
                        items.Add(new WeakReference(container));
                        index++;
                        break;
                    }
                }
            }

            for (; index < list.Items.Count; index++)
            {
                container     = (FrameworkElement)list.ItemContainerGenerator.ContainerFromIndex(index);
                itemTransform = null;
                try
                {
                    itemTransform = container.TransformToVisual(scrollHost);
                }
                catch (ArgumentException)
                {
                    // Ignore failures when not in the visual tree
                    return;
                }

                boundingBox = new Rect(itemTransform.Transform(new Point()), itemTransform.Transform(new Point(container.ActualWidth, container.ActualHeight)));

                if (boundingBox.Top < scrollHost.ActualHeight)
                {
                    items.Add(new WeakReference(container));
                }
                else
                {
                    break;
                }
            }

            return;
        }
Пример #37
0
 private void Select(object sender, MouseButtonEventArgs e)
 {
     var res = ItemsControl.ContainerFromElement(sender as ListBox, e.OriginalSource as DependencyObject) as ListBox;
 }
Пример #38
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            var itemsControl = this.DropInfo.VisualTarget as ItemsControl;

            if (itemsControl != null)
            {
                // Get the position of the item at the insertion index. If the insertion point is
                // to be after the last item, then get the position of the last item and add an
                // offset later to draw it at the end of the list.
                ItemsControl itemParent;

                if (this.DropInfo.VisualTargetItem != null)
                {
                    itemParent = ItemsControl.ItemsControlFromItemContainer(this.DropInfo.VisualTargetItem);
                }
                else
                {
                    itemParent = itemsControl;
                }

                var index = Math.Min(this.DropInfo.InsertIndex, itemParent.Items.Count - 1);

                var lastItemInGroup = false;
                var targetGroup     = this.DropInfo.TargetGroup;
                if (targetGroup != null && targetGroup.IsBottomLevel && this.DropInfo.InsertPosition.HasFlag(RelativeInsertPosition.AfterTargetItem))
                {
                    var indexOf = targetGroup.Items.IndexOf(this.DropInfo.TargetItem);
                    lastItemInGroup = indexOf == targetGroup.ItemCount - 1;
                    if (lastItemInGroup)
                    {
                        index--;
                    }
                }

                var itemContainer = (UIElement)itemParent.ItemContainerGenerator.ContainerFromIndex(index);

                if (itemContainer != null)
                {
                    var    itemRect = new Rect(itemContainer.TranslatePoint(new Point(), this.AdornedElement), itemContainer.RenderSize);
                    Point  point1, point2;
                    double rotation = 0;

                    if (this.DropInfo.VisualTargetOrientation == Orientation.Vertical)
                    {
                        if (this.DropInfo.InsertIndex == itemParent.Items.Count || lastItemInGroup)
                        {
                            itemRect.Y += itemContainer.RenderSize.Height;
                        }

                        point1 = new Point(itemRect.X, itemRect.Y);
                        point2 = new Point(itemRect.Right, itemRect.Y);
                    }
                    else
                    {
                        var itemRectX = itemRect.X;

                        if (this.DropInfo.VisualTargetFlowDirection == FlowDirection.LeftToRight && this.DropInfo.InsertIndex == itemParent.Items.Count)
                        {
                            itemRectX += itemContainer.RenderSize.Width;
                        }
                        else if (this.DropInfo.VisualTargetFlowDirection == FlowDirection.RightToLeft && this.DropInfo.InsertIndex != itemParent.Items.Count)
                        {
                            itemRectX += itemContainer.RenderSize.Width;
                        }

                        point1   = new Point(itemRectX, itemRect.Y);
                        point2   = new Point(itemRectX, itemRect.Bottom);
                        rotation = 90;
                    }

                    drawingContext.DrawLine(m_Pen, point1, point2);
                    this.DrawTriangle(drawingContext, point1, rotation);
                    this.DrawTriangle(drawingContext, point2, 180 + rotation);
                }
            }
        }
Пример #39
0
 public static void SetEmptyCount(ItemsControl element, int value) => element.SetValue(EmptyCountProperty, value);
 override void OnApplyTemplate()
 {
     base.OnApplyTemplate();
     _itemsControl = GetTemplateChild("TemplateItems") as ItemsControl;
     InitItemsSource();
 }
 private static Panel GetItemsHost(ItemsControl itemsControl)
 {
     Debug.Assert(itemsControl != null);
     return(ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel);
 }
Пример #42
0
 public static void SetInitialize(ItemsControl element, bool value) => element.SetValue(InitializeProperty, value);
        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();
                var 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);
                    }
                }

                var itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);

                // Ensure that the generator for this panel has been created.
#pragma warning disable 168
                var children = itemsHostPanel.Children;
#pragma warning restore 168

                for (int i = 0, count = container.Items.Count; i < count; i++)
                {
                    var subContainer = (TreeViewItem)container.ItemContainerGenerator.
                                       ContainerFromIndex(i);
                    if (subContainer == null)
                    {
                        continue;
                    }

                    subContainer.BringIntoView();

                    // Search the next level for the object.
                    var 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);
        }
Пример #44
0
        public static T FindFirstChild <T>(this DependencyObject dependencyObject, string name = null) where T : class
        {
            if (dependencyObject is T)
            {
                if (!string.IsNullOrWhiteSpace(name) && dependencyObject is FrameworkElement)
                {
                    FrameworkElement frameworkElement = (FrameworkElement)dependencyObject;
                    if (string.Equals(frameworkElement.Name, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(dependencyObject as T);
                    }
                }
                else
                {
                    return(dependencyObject as T);
                }
            }
            Panel panel = dependencyObject as Panel;

            if (panel != null)
            {
                foreach (UIElement panelItem in panel.Children)
                {
                    T child = panelItem.FindFirstChild <T>(name);
                    if (child != null)
                    {
                        return(child);
                    }
                }
            }
            ContentControl contentControl = dependencyObject as ContentControl;

            if (contentControl != null)
            {
                UIElement visual = contentControl.Content as UIElement;
                if (visual != null)
                {
                    T child = visual.FindFirstChild <T>(name);
                    if (child != null)
                    {
                        return(child);
                    }
                }
            }
            ItemsControl itemsControl = dependencyObject as ItemsControl;

            if (itemsControl != null)
            {
                foreach (object itemsControlItem in itemsControl.Items)
                {
                    UIElement uiElement = itemsControlItem as UIElement;
                    if (uiElement == null)
                    {
                        continue;
                    }
                    T child = uiElement.FindFirstChild <T>(name);
                    if (child != null)
                    {
                        return(child);
                    }
                }
            }
            return(null);
        }
Пример #45
0
 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();
     }
 }
Пример #46
0
        public void CreateControl(out FrameworkElement control)
        {
            //<DataTemplate DataType="{x:Type options:OptionEntityList}">
            //    <Grid>
            //        <Grid.RowDefinitions>
            //            <RowDefinition Height="*" />
            //            <RowDefinition Height="Auto" />
            //        </Grid.RowDefinitions>
            //
            //        <ItemsControl Grid.Row="0"
            //                      ItemsSource="{Binding EntityCollection}"
            //                      HorizontalAlignment="Center">
            //            <ItemsControl.ItemsPanel>
            //                <ItemsPanelTemplate>
            //                    <StackPanel Orientation="Vertical" IsItemsHost="True" />
            //                </ItemsPanelTemplate>
            //            </ItemsControl.ItemsPanel>
            //            <ItemsControl.Template>
            //                <ControlTemplate TargetType="{x:Type ItemsControl}">
            //                    <ScrollViewer>
            //                        <ItemsPresenter />
            //                    </ScrollViewer>
            //                </ControlTemplate>
            //            </ItemsControl.Template>
            //        </ItemsControl>
            //
            //        <Grid Grid.Row="1"
            //              Margin="0,5,0,5">
            //            <Grid.ColumnDefinitions>
            //                <ColumnDefinition Width="*" />
            //                <ColumnDefinition Width="*" />
            //            </Grid.ColumnDefinitions>
            //
            //            <Button Grid.Column="0"
            //                    HorizontalAlignment="Center"
            //                    Content="{x:Static data:AutomatonStrings.Button_SelectAll}"
            //                    IsEnabled="{Binding HasUnselected}"
            //                    Command="{Binding SelectAll}" />
            //
            //            <Button Grid.Column="1"
            //                    HorizontalAlignment="Center"
            //                    Content="{x:Static data:AutomatonStrings.Button_DeselectAll}"
            //                    IsEnabled="{Binding HasSelected}"
            //                    Command="{Binding DeselectAll}" />
            //        </Grid>
            //    </Grid>
            //</DataTemplate>

            var mainGrid = new Grid();

            mainGrid.RowDefinitions.Add(new RowDefinition()
            {
                Height = GridLength.Auto
            });
            mainGrid.RowDefinitions.Add(new RowDefinition()
            {
                Height = GridLength.Auto
            });
            mainGrid.DataContext = optionValueHolder;

            var itemsControl = new ItemsControl()
            {
                HorizontalAlignment = HorizontalAlignment.Center,
            };

            itemsControl.SetBinding(ItemsControl.ItemsSourceProperty, nameof(optionValueHolder.EntityCollection));
            mainGrid.Children.Add(itemsControl);

            var buttonGrid = new Grid()
            {
                Margin = new Thickness(0, 5, 0, 5)
            };

            buttonGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(50, GridUnitType.Star)
            });
            buttonGrid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(50, GridUnitType.Star)
            });

            var selectAllButton = new Button()
            {
                HorizontalAlignment = HorizontalAlignment.Center,
                Content             = AutomatonStrings.Button_SelectAll,
            };

            selectAllButton.SetBinding(UIElement.IsEnabledProperty, nameof(optionValueHolder.HasUnselected));
            selectAllButton.SetBinding(ButtonBase.CommandProperty, nameof(optionValueHolder.SelectAll));
            buttonGrid.Children.Add(selectAllButton);

            var deselectAllButton = new Button()
            {
                HorizontalAlignment = HorizontalAlignment.Center,
                Content             = AutomatonStrings.Button_DeselectAll,
            };

            deselectAllButton.SetBinding(UIElement.IsEnabledProperty, nameof(optionValueHolder.HasSelected));
            deselectAllButton.SetBinding(ButtonBase.CommandProperty, nameof(optionValueHolder.DeselectAll));
            buttonGrid.Children.Add(deselectAllButton);
            Grid.SetColumn(deselectAllButton, 1);

            mainGrid.Children.Add(buttonGrid);
            Grid.SetRow(buttonGrid, 1);

            control = mainGrid;
        }
Пример #47
0
 /// <summary>
 /// 获取数据源IDictionary&lt;T&gt;
 /// </summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="control"></param>
 /// <returns></returns>
 public static IDictionary <TKey, TValue> GetItemsSource <TKey, TValue>(this ItemsControl control)
 => control.ItemsSource as IDictionary <TKey, TValue>;
Пример #48
0
        public static Type GetItemContainerType(this ItemsControl itemsControl, out bool isItemContainer)
        {
            // determines if the itemsControl is not a ListView, ListBox or TreeView
            isItemContainer = false;

            if (typeof(TabControl).IsAssignableFrom(itemsControl.GetType()))
            {
                return(typeof(TabItem));
            }

            if (typeof(DataGrid).IsAssignableFrom(itemsControl.GetType()))
            {
                return(typeof(DataGridRow));
            }

            // There is no safe way to get the item container type for an ItemsControl.
            // First hard-code the types for the common ItemsControls.
            //if (itemsControl.GetType().IsAssignableFrom(typeof(ListView)))
            if (typeof(ListView).IsAssignableFrom(itemsControl.GetType()))
            {
                return(typeof(ListViewItem));
            }
            //if (itemsControl.GetType().IsAssignableFrom(typeof(ListBox)))
            else if (typeof(ListBox).IsAssignableFrom(itemsControl.GetType()))
            {
                return(typeof(ListBoxItem));
            }
            //else if (itemsControl.GetType().IsAssignableFrom(typeof(TreeView)))
            else if (typeof(TreeView).IsAssignableFrom(itemsControl.GetType()))
            {
                return(typeof(TreeViewItem));
            }

            // Otherwise look for the control's ItemsPresenter, get it's child panel and the first
            // child of that *should* be an item container.
            //
            // If the control currently has no items, we're out of luck.
            if (itemsControl.Items.Count > 0)
            {
                var itemsPresenters = itemsControl.GetVisualDescendents <ItemsPresenter>();

                foreach (var itemsPresenter in itemsPresenters)
                {
                    if (VisualTreeHelper.GetChildrenCount(itemsPresenter) > 0)
                    {
                        var panel         = VisualTreeHelper.GetChild(itemsPresenter, 0);
                        var itemContainer = VisualTreeHelper.GetChildrenCount(panel) > 0
              ? VisualTreeHelper.GetChild(panel, 0)
              : null;

                        // Ensure that this actually *is* an item container by checking it with
                        // ItemContainerGenerator.
                        if (itemContainer != null &&
                            itemsControl.ItemContainerGenerator.IndexFromContainer(itemContainer) != -1)
                        {
                            isItemContainer = true;
                            return(itemContainer.GetType());
                        }
                    }
                }
            }

            return(null);
        }
Пример #49
0
 private static void ClearItemsControlManager(ItemsControl itemsControl)
 {
     itemsControl.ClearValue(ItemsControlManagerProperty);
 }
Пример #50
0
 public static bool GetShiftWheelScrollsHorizontally(ItemsControl element) => (bool)element.GetValue(ShiftWheelScrollsHorizontallyProperty);
Пример #51
0
 private static ItemsControlManager GetItemsControlManager(ItemsControl itemsControl)
 {
     return((ItemsControlManager)itemsControl.GetValue(ItemsControlManagerProperty));
 }
Пример #52
0
 public static void SetShiftWheelScrollsHorizontally(ItemsControl element, bool value) => element.SetValue(ShiftWheelScrollsHorizontallyProperty, value);
Пример #53
0
 bool ItemsControlStringIdComparer(ItemsControl control, string firstId, string secondId, string lastId)
 {
     return(((EnumMemberInfo)control.Items.GetItemAt(0)).Id.ToString() == firstId &&
            ((EnumMemberInfo)control.Items.GetItemAt(1)).Id.ToString() == secondId &&
            ((EnumMemberInfo)control.Items.GetItemAt(2)).Id.ToString() == lastId);
 }
Пример #54
0
        private static void CreateDragAdorner(DropInfo dropInfo)
        {
            var dragInfo         = m_DragInfo;
            var template         = GetDragAdornerTemplate(dragInfo.VisualSource);
            var templateSelector = GetDragAdornerTemplateSelector(dragInfo.VisualSource);

            UIElement adornment = null;

            var useDefaultDragAdorner = GetUseDefaultDragAdorner(dragInfo.VisualSource);
            var useVisualSourceItemSizeForDragAdorner = GetUseVisualSourceItemSizeForDragAdorner(dragInfo.VisualSource);

            if (template == null && templateSelector == null && useDefaultDragAdorner)
            {
                template = dragInfo.VisualSourceItem.GetCaptureScreenDataTemplate(dragInfo.VisualSourceFlowDirection);
            }

            if (template != null || templateSelector != null)
            {
                if (dragInfo.Data is IEnumerable && !(dragInfo.Data is string))
                {
                    if (!useDefaultDragAdorner && ((IEnumerable)dragInfo.Data).Cast <object>().Count() <= 10)
                    {
                        var itemsControl = new ItemsControl();
                        itemsControl.ItemsSource          = (IEnumerable)dragInfo.Data;
                        itemsControl.ItemTemplate         = template;
                        itemsControl.ItemTemplateSelector = templateSelector;
                        itemsControl.Tag = dragInfo;

                        if (useVisualSourceItemSizeForDragAdorner)
                        {
                            var bounds = VisualTreeHelper.GetDescendantBounds(dragInfo.VisualSourceItem);
                            itemsControl.SetValue(FrameworkElement.MinWidthProperty, bounds.Width);
                        }

                        // The ItemsControl doesn't display unless we create a grid to contain it.
                        // Not quite sure why we need this...
                        var grid = new Grid();
                        grid.Children.Add(itemsControl);
                        adornment = grid;
                    }
                }
                else
                {
                    var contentPresenter = new ContentPresenter();
                    contentPresenter.Content                 = dragInfo.Data;
                    contentPresenter.ContentTemplate         = template;
                    contentPresenter.ContentTemplateSelector = templateSelector;
                    contentPresenter.Tag = dragInfo;

                    if (useVisualSourceItemSizeForDragAdorner)
                    {
                        var bounds = VisualTreeHelper.GetDescendantBounds(dragInfo.VisualSourceItem);
                        contentPresenter.SetValue(FrameworkElement.MinWidthProperty, bounds.Width);
                        contentPresenter.SetValue(FrameworkElement.MinHeightProperty, bounds.Height);
                    }

                    adornment = contentPresenter;
                }
            }

            if (adornment != null)
            {
                if (useDefaultDragAdorner)
                {
                    adornment.Opacity = GetDefaultDragAdornerOpacity(dragInfo.VisualSource);
                }

                var rootElement = RootElementFinder.FindRoot(dropInfo.VisualTarget ?? dragInfo.VisualSource);
                DragAdorner = new DragAdorner(rootElement, adornment, GetDragAdornerTranslation(dragInfo.VisualSource));
            }
        }
Пример #55
0
        public void DataTemplate_Created_Content_Should_Be_NameScope()
        {
            var items = new object[]
            {
                "foo",
            };

            var target = new ItemsControl
            {
                Template = GetTemplate(),
                Items = items,
            };

            target.ApplyTemplate();
            target.Presenter.ApplyTemplate();

            var container = (ContentPresenter)target.Presenter.Panel.LogicalChildren[0];
            container.UpdateChild();

            Assert.NotNull(NameScope.GetNameScope((TextBlock)container.Child));
        }
Пример #56
0
        /// <summary>
        /// Initializes a new instance of the DragInfo class.
        /// </summary>
        ///
        /// <param name="sender">
        /// The sender of the mouse event that initiated the drag.
        /// </param>
        ///
        /// <param name="e">
        /// The mouse event that initiated the drag.
        /// </param>
        public DragInfo(object sender, MouseButtonEventArgs e)
        {
            this.Effects              = DragDropEffects.None;
            this.MouseButton          = e.ChangedButton;
            this.VisualSource         = sender as UIElement;
            this.DragStartPosition    = e.GetPosition(this.VisualSource);
            this.DragDropCopyKeyState = DragDrop.GetDragDropCopyKeyState(this.VisualSource);

            var dataFormat = DragDrop.GetDataFormat(this.VisualSource);

            if (dataFormat != null)
            {
                this.DataFormat = dataFormat;
            }

            var sourceElement = e.OriginalSource as UIElement;

            // If we can't cast object as a UIElement it might be a FrameworkContentElement, if so try and use its parent.
            if (sourceElement == null && e.OriginalSource is FrameworkContentElement)
            {
                sourceElement = ((FrameworkContentElement)e.OriginalSource).Parent as UIElement;
            }

            if (sender is ItemsControl)
            {
                var itemsControl = (ItemsControl)sender;

                this.SourceGroup = itemsControl.FindGroup(this.DragStartPosition);
                this.VisualSourceFlowDirection = itemsControl.GetItemsPanelFlowDirection();

                UIElement item = null;
                if (sourceElement != null)
                {
                    item = itemsControl.GetItemContainer(sourceElement);
                }

                if (item == null)
                {
                    if (DragDrop.GetDragDirectlySelectedOnly(this.VisualSource))
                    {
                        item = itemsControl.GetItemContainerAt(e.GetPosition(itemsControl));
                    }
                    else
                    {
                        item = itemsControl.GetItemContainerAt(e.GetPosition(itemsControl), itemsControl.GetItemsPanelOrientation());
                    }
                }

                if (item != null)
                {
                    // Remember the relative position of the item being dragged
                    this.PositionInDraggedItem = e.GetPosition(item);

                    var itemParent = ItemsControl.ItemsControlFromItemContainer(item);

                    if (itemParent != null)
                    {
                        this.SourceCollection = itemParent.ItemsSource ?? itemParent.Items;
                        if (itemParent != itemsControl)
                        {
                            var tvItem = item as TreeViewItem;
                            if (tvItem != null)
                            {
                                var tv = tvItem.GetVisualAncestor <TreeView>();
                                if (tv != null && tv != itemsControl && !tv.IsDragSource())
                                {
                                    return;
                                }
                            }
                            else if (itemsControl.ItemContainerGenerator.IndexFromContainer(itemParent) < 0 && !itemParent.IsDragSource())
                            {
                                return;
                            }
                        }
                        this.SourceIndex = itemParent.ItemContainerGenerator.IndexFromContainer(item);
                        this.SourceItem  = itemParent.ItemContainerGenerator.ItemFromContainer(item);
                    }
                    else
                    {
                        this.SourceIndex = -1;
                    }

                    var selectedItems = itemsControl.GetSelectedItems().OfType <object>().Where(i => i != CollectionView.NewItemPlaceholder).ToList();
                    this.SourceItems = selectedItems;

                    // Some controls (I'm looking at you TreeView!) haven't updated their
                    // SelectedItem by this point. Check to see if there 1 or less item in
                    // the SourceItems collection, and if so, override the control's SelectedItems with the clicked item.
                    //
                    // The control has still the old selected items at the mouse down event, so we should check this and give only the real selected item to the user.
                    if (selectedItems.Count <= 1 || this.SourceItem != null && !selectedItems.Contains(this.SourceItem))
                    {
                        this.SourceItems = Enumerable.Repeat(this.SourceItem, 1);
                    }

                    this.VisualSourceItem = item;
                }
                else
                {
                    this.SourceCollection = itemsControl.ItemsSource ?? itemsControl.Items;
                }
            }
            else
            {
                this.SourceItem = (sender as FrameworkElement)?.DataContext;
                if (this.SourceItem != null)
                {
                    this.SourceItems = Enumerable.Repeat(this.SourceItem, 1);
                }
                this.VisualSourceItem      = sourceElement;
                this.PositionInDraggedItem = sourceElement != null?e.GetPosition(sourceElement) : this.DragStartPosition;
            }

            if (this.SourceItems == null)
            {
                this.SourceItems = Enumerable.Empty <object>();
            }
        }
Пример #57
0
 public NoomDestination(ContentControl target, ItemsControl items, ItemsControl paging)
 {
     this.target = target;
     this.items  = items;
     this.paging = paging;
 }
Пример #58
0
 public static int GetEmptyCount(ItemsControl element) => (int)element.GetValue(EmptyCountProperty);
Пример #59
0
        // From all of our children, set the InMenuMode property
        // If turning this property off, recurse to all submenus
        internal static void SetSuspendingPopupAnimation(ItemsControl menu, MenuItem ignore, bool suspend)
        {
            // menu can be either a MenuBase or MenuItem
            if (menu != null)
            {
                int itemsCount = menu.Items.Count;

                for (int i = 0; i < itemsCount; i++)
                {
                    MenuItem mi = menu.ItemContainerGenerator.ContainerFromIndex(i) as MenuItem;

                    if (mi != null && mi != ignore && mi.IsSuspendingPopupAnimation != suspend)
                    {
                        mi.IsSuspendingPopupAnimation = suspend;

                        // If leaving menu mode, clear property on all
                        // submenus of this menu
                        if (!suspend)
                        {
                            SetSuspendingPopupAnimation(mi, null, suspend);
                        }
                    }
                }
            }
        }
Пример #60
0
        /// <summary>
        /// Finds the provided object in an ItemsControl's children and selects it
        /// </summary>
        /// <param name="parentContainer">The parent container whose children will be searched for the selected item</param>
        /// <param name="itemToSelect">The item to select</param>
        /// <returns>True if the item is found and selected, false otherwise</returns>
        private static bool ExpandAndSelectItem(ItemsControl parentContainer, string itemToSelect)
        {
            //check all items at the current level
            foreach (Object item in parentContainer.Items)
            {
                TreeViewItem currentContainer =
                    parentContainer.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

                //if the data item matches the item we want to select, set the corresponding
                //TreeViewItem IsSelected to true
                if (currentContainer != null)
                {
                    var drive = currentContainer.Tag as DriveInfo;
                    var path  = currentContainer.Tag as DirectoryInfo;
                    if (drive != null && drive.RootDirectory.FullName == itemToSelect)
                    {
                        currentContainer.IsSelected = true;
                        currentContainer.BringIntoView();
                        currentContainer.Focus();

                        //the item was found
                        return(true);
                    }

                    if (path != null && path.FullName == itemToSelect)
                    {
                        currentContainer.IsSelected = true;
                        currentContainer.BringIntoView();
                        currentContainer.Focus();

                        //the item was found
                        return(true);
                    }
                }
            }

            //if we get to this point, the selected item was not found at the current level, so we must check the children
            foreach (Object item in parentContainer.Items)
            {
                TreeViewItem currentContainer = parentContainer.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                var          drive            = currentContainer.Tag as DriveInfo;
                var          path             = currentContainer.Tag as DirectoryInfo;
                if (drive != null && !itemToSelect.StartsWith(drive.RootDirectory.FullName))
                {
                    continue;
                }

                if (path != null && !itemToSelect.StartsWith(path.FullName))
                {
                    continue;
                }

                //if children exist
                if (currentContainer != null && currentContainer.Items.Count > 0)
                {
                    //keep track of if the TreeViewItem was expanded or not
                    bool wasExpanded = currentContainer.IsExpanded;

                    //expand the current TreeViewItem so we can check its child TreeViewItems
                    currentContainer.IsExpanded = true;

                    //if the TreeViewItem child containers have not been generated, we must listen to
                    //the StatusChanged event until they are
                    if (currentContainer.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
                    {
                        //store the event handler in a variable so we can remove it (in the handler itself)
                        EventHandler eh = null;
                        eh = new EventHandler(delegate
                        {
                            if (currentContainer.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
                            {
                                if (ExpandAndSelectItem(currentContainer, itemToSelect) == false)
                                {
                                    //The assumption is that code executing in this EventHandler is the result of the parent not
                                    //being expanded since the containers were not generated.
                                    //since the itemToSelect was not found in the children, collapse the parent since it was previously collapsed
                                    currentContainer.IsExpanded = false;
                                }

                                //remove the StatusChanged event handler since we just handled it (we only needed it once)
                                currentContainer.ItemContainerGenerator.StatusChanged -= eh;
                            }
                        });
                        currentContainer.ItemContainerGenerator.StatusChanged += eh;
                    }
                    else //otherwise the containers have been generated, so look for item to select in the children
                    {
                        if (ExpandAndSelectItem(currentContainer, itemToSelect) == false)
                        {
                            //restore the current TreeViewItem's expanded state
                            currentContainer.IsExpanded = wasExpanded;
                        }
                        else //otherwise the node was found and selected, so return true
                        {
                            return(true);
                        }
                    }
                }
            }

            //no item was found
            return(false);
        }