private void CreateItemCollectionAndGenerator() { _items = new ItemCollection(this); // the generator must attach its collection change handler before // the control itself, so that the generator is up-to-date by the // time the control tries to use it (bug 892806 et al.) _itemContainerGenerator = new ItemContainerGenerator(this); _itemContainerGenerator.ChangeAlternationCount(); ((INotifyCollectionChanged)_items).CollectionChanged += new NotifyCollectionChangedEventHandler(OnItemCollectionChanged); if (IsInitPending) { _items.BeginInit(); } else if (IsInitialized) { _items.BeginInit(); _items.EndInit(); } ((INotifyCollectionChanged)_groupStyle).CollectionChanged += new NotifyCollectionChangedEventHandler(OnGroupStyleChanged); }
private ItemContainerGenerator(ItemContainerGenerator parent, IGeneratorHost host, DependencyObject peer, int level) { _parent = parent; _host = host; _peer = peer; _level = level; OnRefresh(); }
public VisualCommentsHelper(Dispatcher disp, ItemContainerGenerator gen, Comment placeholder) { _gen = gen; _placeholder = placeholder; disp.BeginInvoke(new Action(DeferredFocusSet), System.Windows.Threading.DispatcherPriority.Background, null); }
/// <summary> /// Selects the tree view item. /// </summary> /// <param name="owningItemGenerator">The owning item generator.</param> /// <param name="dataItem">The data item.</param> public static void SelectTreeViewItem(ItemContainerGenerator owningItemGenerator, object dataItem) { if (owningItemGenerator == null) return; var treeViewItem = owningItemGenerator.ContainerFromItem(dataItem) as TreeViewItem; if (treeViewItem != null) { treeViewItem.IsSelected = true; } }
/// <summary> /// Expands the tree view item. /// </summary> /// <param name="owningItemGenerator">The owning item generator.</param> /// <param name="dataItem">The data item.</param> /// <returns></returns> public static TreeViewItem ExpandTreeViewItem(ItemContainerGenerator owningItemGenerator, object dataItem) { if (owningItemGenerator == null) return null; var treeViewItem = owningItemGenerator.ContainerFromItem(dataItem) as TreeViewItem; if (treeViewItem != null) { treeViewItem.IsExpanded = true; } return treeViewItem; }
private static TreeViewItem ContainerFromItem(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, object item) { foreach (object curChildItem in itemCollection) { TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); TreeViewItem containerThatMightContainItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item); if (containerThatMightContainItem != null) return containerThatMightContainItem; TreeViewItem recursionResult = ContainerFromItem(parentContainer.ItemContainerGenerator, parentContainer.Items, item); if (recursionResult != null) return recursionResult; } return null; }
private static object ItemFromContainer(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, TreeViewItem container) { foreach (object curChildItem in itemCollection) { TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); TreeViewItem itemThatMightBelongToContainer = (TreeViewItem)parentContainer.ItemContainerGenerator.ItemFromContainer(container); if (itemThatMightBelongToContainer != null) return itemThatMightBelongToContainer; TreeViewItem recursionResult = ItemFromContainer(parentContainer.ItemContainerGenerator, parentContainer.Items, container) as TreeViewItem; if (recursionResult != null) return recursionResult; } return null; }
static void ContainerStatusChanged(DataGrid dataGrid, ItemContainerGenerator generator) { if (generator != null && generator.Status == GeneratorStatus.ContainersGenerated && dataGrid.SelectedItems.Count == 1) { var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.SelectedItems[0]); if (row != null) { var cell = DataGridHelper.GetCell(dataGrid, row.GetIndex(), 1); if (cell != null) { SelectCellMethod.Invoke(dataGrid, new object[] { cell, false, false, false }); } } } }
private static bool Deselect(ItemContainerGenerator itemContainerGenerator) { if (itemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return false; foreach (object item in itemContainerGenerator.Items) { TreeViewItem treeViewItem = (TreeViewItem)itemContainerGenerator.ContainerFromItem(item); if (treeViewItem.IsSelected) { treeViewItem.IsSelected = false; return true; } bool retVal = Deselect(treeViewItem.ItemContainerGenerator); if (retVal) return true; } return false; }
private static object ExpandPathToNodeAndSelectBestMatchRecursively(UIElement treeView, ItemContainerGenerator owningItemGenerator, object currentNodeDataItem, Func<object, IEnumerable> childNodeDataItemSelector, Func<object, string, int, bool> matchPathToNode, string[] pathTokens, int tokenIndex) { var foundNode = default(object); var currentToken = pathTokens[tokenIndex]; // Check whether this is the node we are looking for. if ((matchPathToNode(currentNodeDataItem, currentToken, tokenIndex))) { // Expand this item before looking at the children. The update layout call is needed because although the // item has been expanded, none of the expanded items will have been created, and so calls to the // treeViewItem.ItemGenerator will return null until the UI has had a chance to create the child items. var currentTreeViewItem = ExpandTreeViewItem(owningItemGenerator, currentNodeDataItem); if (treeView != null) { treeView.UpdateLayout(); } if (tokenIndex < pathTokens.Length - 1) { // Now see if we can continue to match any of the children. var currentChildItemCenerator = currentTreeViewItem == null ? null : currentTreeViewItem.ItemContainerGenerator; var childNodes = childNodeDataItemSelector(currentNodeDataItem); if (childNodes != null) { foreach (var childNode in childNodes) { foundNode = ExpandPathToNodeAndSelectBestMatchRecursively(treeView, currentChildItemCenerator, childNode, childNodeDataItemSelector, matchPathToNode, pathTokens, tokenIndex + 1); if (foundNode != null) { break; } } } } // This node is a match, but none of the children are (or there are no children). Select this node instead. if (foundNode == null) { foundNode = currentNodeDataItem; SelectTreeViewItem(owningItemGenerator, currentNodeDataItem); } } return foundNode; }
public void ItemContainerGeneratorBasicTest() { TestGeneratorHost host = new TestGeneratorHost(); ItemContainerGenerator generator = new ItemContainerGenerator(host); ItemsChangedEventArgs lastChangedArg = null; generator.ItemsChanged += (sender, e) => lastChangedArg = e; host.View.Add("item1"); Assert.AreEqual(NotifyCollectionChangedAction.Add, lastChangedArg.Action); Assert.AreEqual(0, lastChangedArg.NewStartingIndex); Assert.AreEqual(1, lastChangedArg.ItemsCount); Assert.AreEqual(0, lastChangedArg.ContainersCount); FrameworkElement container1 = generator.Generate(0); Assert.IsTrue(host.Containers.ContainsKey("item1")); Assert.AreEqual("item1", container1.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); host.View[0] = "item2"; Assert.IsFalse(host.Containers.ContainsKey("item1")); Assert.IsTrue(host.Containers.ContainsKey("item2")); Assert.IsNull(container1.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); FrameworkElement container2 = generator.Generate(0); Assert.IsTrue(host.Containers.ContainsKey("item2")); Assert.AreEqual("item2", container2.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); host.View.Remove("item2"); Assert.IsFalse(host.Containers.ContainsKey("item2")); Assert.IsNull(container2.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); host.View.Add("item3"); Assert.IsFalse(host.Containers.ContainsKey("item3")); FrameworkElement container3 = generator.Generate(0); Assert.IsTrue(host.Containers.ContainsKey("item3")); Assert.AreEqual("item3", container3.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); generator.Dispose(); Assert.IsFalse(host.Containers.ContainsKey("item3")); Assert.IsNull(container3.GetValue(TestGeneratorHost.ItemForItemContainerProperty)); }
private void ExpandNextItemInQueueAndSelectIfLastItem(ItemCollection items, ItemContainerGenerator itemContainerGenerator) { var sampleName = _queueOfIndividualnodesToExpandAndSelectTheLast.Dequeue(); var sample = items.FirstOrDefault(s => ( ((s is Sample) && ((Sample)s).Name == sampleName) || ((s is Group) && ((Group)s).Name == sampleName)) ); if (sample == null) return; var container = (TreeViewItem)itemContainerGenerator.ContainerFromItem(sample); if (_queueOfIndividualnodesToExpandAndSelectTheLast.Count == 0) { container.IsSelected = true; } else { ExpandNextItemInQueueAndSelectIfLastItem(container.Items, container.ItemContainerGenerator); } }
//------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods // apply styles described in View. private void ApplyNewView() { ViewBase newView = View; if (newView != null) { // update default style key of ListView DefaultStyleKey = newView.DefaultStyleKey; } else { ClearValue(DefaultStyleKeyProperty); } // Encounter a new view after loaded means user is switching view. // Force to regenerate all containers. if (IsLoaded) { ItemContainerGenerator.Refresh(); } }
private void ConnectToGenerator() { Debug.Assert(_itemContainerGenerator == null, "Attempted to connect to a generator when Panel._itemContainerGenerator is non-null."); ItemsControl itemsOwner = ItemsControl.GetItemsOwner(this); if (itemsOwner == null) { // This can happen if IsItemsHost=true, but the panel is not nested in an ItemsControl throw new InvalidOperationException(SR.Get(SRID.Panel_ItemsControlNotFound)); } IItemContainerGenerator itemsOwnerGenerator = itemsOwner.ItemContainerGenerator; if (itemsOwnerGenerator != null) { _itemContainerGenerator = itemsOwnerGenerator.GetItemContainerGeneratorForPanel(this); if (_itemContainerGenerator != null) { _itemContainerGenerator.ItemsChanged += new ItemsChangedEventHandler(OnItemsChanged); ((IItemContainerGenerator)_itemContainerGenerator).RemoveAll(); } } }
private static TreeViewItem ContainerFromItem(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, object item) { foreach (object curChildItem in itemCollection) { TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (parentContainer == null) { return(null); } TreeViewItem containerThatMightContainItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item); if (containerThatMightContainItem != null) { return(containerThatMightContainItem); } TreeViewItem recursionResult = ContainerFromItem(parentContainer.ItemContainerGenerator, parentContainer.Items, item); if (recursionResult != null) { return(recursionResult); } } return(null); }
private static object ItemFromContainer(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, TreeViewItem container) { foreach (object curChildItem in itemCollection) { TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (parentContainer == null) { return(null); } TreeViewItem itemThatMightBelongToContainer = (TreeViewItem)parentContainer.ItemContainerGenerator.ItemFromContainer(container); if (itemThatMightBelongToContainer != null) { return(itemThatMightBelongToContainer); } TreeViewItem recursionResult = ItemFromContainer(parentContainer.ItemContainerGenerator, parentContainer.Items, container) as TreeViewItem; if (recursionResult != null) { return(recursionResult); } } return(null); }
private static TreeViewItem FindContainer(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, Predicate <TreeViewItem> condition) { foreach (object curChildItem in itemCollection) { TreeViewItem containerThatMightMeetTheCondition = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (containerThatMightMeetTheCondition == null) { return(null); } if (condition(containerThatMightMeetTheCondition)) { return(containerThatMightMeetTheCondition); } TreeViewItem recursionResult = FindContainer(containerThatMightMeetTheCondition.ItemContainerGenerator, containerThatMightMeetTheCondition.Items, condition); if (recursionResult != null) { return(recursionResult); } } return(null); }
/// <summary>Finds the TreeViewItem from the collection.</summary> /// <param name="parentItemContainerGenerator">The parent item container.</param> /// <param name="itemCollection">The item collection.</param> /// <param name="predicate">The TreeViewItem.</param> /// <returns>The TreeViewItem found.</returns> static TreeViewItem FindTreeViewItem( ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, Predicate<TreeViewItem> predicate) { foreach (var trvItem in from object item in itemCollection select item as TreeViewItem ?? (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(item)) { if (predicate(trvItem)) { return trvItem; } TreeViewItem nestedSearchResult = FindTreeViewItem( trvItem.ItemContainerGenerator, trvItem.Items, predicate); if (nestedSearchResult != null) { return nestedSearchResult; } } return null; }
void InvokeItemsChanged(object o, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: SetLogicalParent(native, e.NewItems); break; case NotifyCollectionChangedAction.Remove: SetLogicalParent(IntPtr.Zero, e.OldItems); break; case NotifyCollectionChangedAction.Replace: SetLogicalParent(IntPtr.Zero, e.OldItems); SetLogicalParent(native, e.NewItems); break; } ItemContainerGenerator.OnOwnerItemsItemsChanged(o, e); if (!itemsIsDataBound) { OnItemsChanged(e); } }
private int ElementIndex(ListBoxItem listItem) { return(ItemContainerGenerator.IndexFromContainer(listItem)); }
/// <summary> /// Treeview doesn't have a simple clear selection /// </summary> /// <remarks> /// Got this here: /// http://stackoverflow.com/questions/676819/wpf-treeview-clear-selection /// </remarks> private static void ClearTreeViewSelection(ItemCollection items, ItemContainerGenerator containerGenerator) { if (items != null && containerGenerator != null) { for (int cntr = 0; cntr < items.Count; cntr++) { // Can't use item directly, because it could be any UIElement TreeViewItem itemContainer = containerGenerator.ContainerFromIndex(cntr) as TreeViewItem; if (itemContainer != null) { // Recurse ClearTreeViewSelection(itemContainer.Items, itemContainer.ItemContainerGenerator); itemContainer.IsSelected = false; } } } }
private static TreeViewItem FindContainer(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, Predicate<TreeViewItem> condition) { foreach (object curChildItem in itemCollection) { TreeViewItem containerThatMightMeetTheCondition = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (containerThatMightMeetTheCondition == null) return null; if (condition(containerThatMightMeetTheCondition)) return containerThatMightMeetTheCondition; TreeViewItem recursionResult = FindContainer(containerThatMightMeetTheCondition.ItemContainerGenerator, containerThatMightMeetTheCondition.Items, condition); if (recursionResult != null) return recursionResult; } return null; }
private static IEnumerable<TreeViewItem> GetTreeViewItems(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection) { foreach (object curChildItem in itemCollection) { TreeViewItem container = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (container != null) yield return container; foreach (var treeViewItem in GetTreeViewItems(container.ItemContainerGenerator, container.Items)) yield return treeViewItem; } }
// update container and index with current values internal ItemInfo Refresh(ItemContainerGenerator generator) { if (Container == null && Index < 0) { Container = generator.ContainerFromItem(Item); } if (Index < 0 && Container != null) { Index = generator.IndexFromContainer(Container); } if (Container == null && Index >= 0) { Container = generator.ContainerFromIndex(Index); } if (Container == SentinelContainer && Index >= 0) { Container = null; // caller explicitly wants null container } return this; }
private static TreeViewItem ContainerFromItem(ItemContainerGenerator parentItemContainerGenerator, ItemCollection itemCollection, object item) { //todo:needed? //if (parentItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.NotStarted) //{ // IItemContainerGenerator generator = parentItemContainerGenerator; // GeneratorPosition position = generator.GeneratorPositionFromIndex(0); // using (generator.StartAt(position, GeneratorDirection.Forward, true)) // { // foreach (object o in itemCollection) // { // DependencyObject dp = generator.GenerateNext(); // generator.PrepareItemContainer(dp); // } // } //} foreach (object curChildItem in itemCollection) { TreeViewItem parentContainer = (TreeViewItem)parentItemContainerGenerator.ContainerFromItem(curChildItem); if (parentContainer != null) { TreeViewItem containerThatMightContainItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item); if (containerThatMightContainItem != null) return containerThatMightContainItem; TreeViewItem recursionResult = ContainerFromItem(parentContainer.ItemContainerGenerator, parentContainer.Items, item); if (recursionResult != null) return recursionResult; } } return null; }
void UseGenerator(ItemContainerGenerator generator) { if (generator == _generator) return; if (_generator != null) _generator.PanelChanged -= new EventHandler(OnPanelChanged); _generator = generator; if (_generator != null) _generator.PanelChanged += new EventHandler(OnPanelChanged); }
public BatchGenerator(ItemContainerGenerator factory) { _factory = factory; _factory._isGeneratingBatches = true; _factory.SetStatus(GeneratorStatus.GeneratingContainers); }
private void CreateItemCollectionAndGenerator() { _items = new ItemCollection(this); // ItemInfos must get adjusted before the generator's change handler is called, // so that any new ItemInfos arising from the generator don't get adjusted by mistake // (see Win8 690623). ((INotifyCollectionChanged)_items).CollectionChanged += new NotifyCollectionChangedEventHandler(OnItemCollectionChanged1); // the generator must attach its collection change handler before // the control itself, so that the generator is up-to-date by the // time the control tries to use it (bug 892806 et al.) _itemContainerGenerator = new ItemContainerGenerator(this); _itemContainerGenerator.ChangeAlternationCount(); ((INotifyCollectionChanged)_items).CollectionChanged += new NotifyCollectionChangedEventHandler(OnItemCollectionChanged2); if (IsInitPending) { _items.BeginInit(); } else if (IsInitialized) { _items.BeginInit(); _items.EndInit(); } ((INotifyCollectionChanged)_groupStyle).CollectionChanged += new NotifyCollectionChangedEventHandler(OnGroupStyleChanged); }
private ItemContainerGenerator(ItemContainerGenerator parent, GroupItem groupItem) : this(parent, parent.Host, groupItem, parent.Level + 1) { }
// Token: 0x06004E0E RID: 19982 RVA: 0x0015FCB8 File Offset: 0x0015DEB8 internal void PrepareItemContainer(object item, ItemsControl parentItemsControl) { if (this.Generator == null) { return; } if (this._itemsHost != null) { this._itemsHost.IsItemsHost = true; } bool flag = parentItemsControl != null && VirtualizingPanel.GetIsVirtualizingWhenGrouping(parentItemsControl); if (this.Generator != null) { if (!flag) { this.Generator.Release(); } else { this.Generator.RemoveAllInternal(true); } } ItemContainerGenerator parent = this.Generator.Parent; GroupStyle groupStyle = parent.GroupStyle; Style style = groupStyle.ContainerStyle; if (style == null && groupStyle.ContainerStyleSelector != null) { style = groupStyle.ContainerStyleSelector.SelectStyle(item, this); } if (style != null) { if (!style.TargetType.IsInstanceOfType(this)) { throw new InvalidOperationException(SR.Get("StyleForWrongType", new object[] { style.TargetType.Name, base.GetType().Name })); } base.Style = style; base.WriteInternalFlag2(InternalFlags2.IsStyleSetFromGenerator, true); } if (base.ContentIsItem || !base.HasNonDefaultValue(ContentControl.ContentProperty)) { base.Content = item; base.ContentIsItem = true; } if (!base.HasNonDefaultValue(ContentControl.ContentTemplateProperty)) { base.ContentTemplate = groupStyle.HeaderTemplate; } if (!base.HasNonDefaultValue(ContentControl.ContentTemplateSelectorProperty)) { base.ContentTemplateSelector = groupStyle.HeaderTemplateSelector; } if (!base.HasNonDefaultValue(ContentControl.ContentStringFormatProperty)) { base.ContentStringFormat = groupStyle.HeaderStringFormat; } Helper.ClearVirtualizingElement(this); if (flag) { Helper.SetItemValuesOnContainer(parentItemsControl, this, item); if (this._expander != null) { Helper.SetItemValuesOnContainer(parentItemsControl, this._expander, item); } } }
private TreeViewItem GetTreeViewItem(ItemContainerGenerator containerGenerator, IDataSourceViewModel item) { var container = (TreeViewItem) containerGenerator.ContainerFromItem(item); if (container != null) return container; foreach (object childItem in containerGenerator.Items) { var parent = containerGenerator.ContainerFromItem(childItem) as TreeViewItem; if (parent == null) continue; container = parent.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem; if (container != null) return container; container = GetTreeViewItem(parent.ItemContainerGenerator, item); if (container != null) return container; } return null; }
//------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ internal void PrepareItemContainer(object item, ItemsControl parentItemsControl) { if (Generator == null) { return; // user-declared GroupItem - ignore ( } // If a GroupItem is being recycled set back IsItemsHost if (_itemsHost != null) { _itemsHost.IsItemsHost = true; } bool isVirtualizingWhenGrouping = (parentItemsControl != null && VirtualizingPanel.GetIsVirtualizingWhenGrouping(parentItemsControl)); // Release any previous containers. Also ensures Items and GroupStyle are hooked up correctly if (Generator != null) { if (!isVirtualizingWhenGrouping) { Generator.Release(); } else { Generator.RemoveAllInternal(true /*saveRecycleQueue*/); } } ItemContainerGenerator generator = Generator.Parent; GroupStyle groupStyle = generator.GroupStyle; // apply the container style Style style = groupStyle.ContainerStyle; // no ContainerStyle set, try ContainerStyleSelector if (style == null) { if (groupStyle.ContainerStyleSelector != null) { style = groupStyle.ContainerStyleSelector.SelectStyle(item, this); } } // apply the style, if found if (style != null) { // verify style is appropriate before applying it if (!style.TargetType.IsInstanceOfType(this)) { throw new InvalidOperationException(SR.Get(SRID.StyleForWrongType, style.TargetType.Name, this.GetType().Name)); } this.Style = style; this.WriteInternalFlag2(InternalFlags2.IsStyleSetFromGenerator, true); } // forward the header template information if (ContentIsItem || !HasNonDefaultValue(ContentProperty)) { this.Content = item; ContentIsItem = true; } if (!HasNonDefaultValue(ContentTemplateProperty)) { this.ContentTemplate = groupStyle.HeaderTemplate; } if (!HasNonDefaultValue(ContentTemplateSelectorProperty)) { this.ContentTemplateSelector = groupStyle.HeaderTemplateSelector; } if (!HasNonDefaultValue(ContentStringFormatProperty)) { this.ContentStringFormat = groupStyle.HeaderStringFormat; } // // Clear previously cached items sizes // Helper.ClearVirtualizingElement(this); // // ItemValueStorage: restore saved values for this item onto the new container // if (isVirtualizingWhenGrouping) { Helper.SetItemValuesOnContainer(parentItemsControl, this, item); if (_expander != null) { Helper.SetItemValuesOnContainer(parentItemsControl, _expander, item); } } }
private ListBoxItem ElementAt(int index) { return(ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem); }
void IsDropDownOpenChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { bool open = (bool)e.NewValue; if (_popup != null) { _popup.IsOpen = open; } if (_dropDownToggle != null) { _dropDownToggle.IsChecked = open; } if (open) { ComboBoxItem t = null; FocusedIndex = Items.Count > 0 ? Math.Max(SelectedIndex, 0) : -1; if (FocusedIndex > -1) { t = ItemContainerGenerator.ContainerFromIndex(FocusedIndex) as ComboBoxItem; } // If the ItemsPresenter hasn't attached yet 't' will be null. // When the itemsPresenter attaches, focus will be set when the // item is loaded if (t != null) { t.Focus(); } LayoutUpdated += UpdatePopupSizeAndPosition; OnDropDownOpened(EventArgs.Empty); // Raises UIA Event AutomationPeer peer = ((ComboBox)sender).AutomationPeer; if (peer != null) { peer.RaisePropertyChangedEvent(ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty, ExpandCollapseState.Collapsed, ExpandCollapseState.Expanded); } } else { Focus(); LayoutUpdated -= UpdatePopupSizeAndPosition; OnDropDownClosed(EventArgs.Empty); // Raises UIA Event AutomationPeer peer = ((ComboBox)sender).AutomationPeer; if (peer != null) { peer.RaisePropertyChangedEvent(ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty, ExpandCollapseState.Expanded, ExpandCollapseState.Collapsed); } } UpdateDisplayedItem(open && SelectedItem is UIElement ? null : SelectedItem); UpdateVisualState(true); }
/// <summary> /// Gets the generated (UI) EnhancedTreeViewItem. /// </summary> /// <param name="containerGenerator">The ItemContainerGenerator from the "parent".</param> /// <param name="item">The (bound) item to get the generated UI Item.</param> /// <returns>The generated UI EnhancedTreeViewItem. null if nothing to return.</returns> private static EnhancedTreeViewItem ContainerFromItem(ItemContainerGenerator containerGenerator, object item) { if (containerGenerator != null) { var container = containerGenerator.ContainerFromItem(item) as EnhancedTreeViewItem; if (container != null) { return container; } // Get items from Container through Reflection. This Property is only public in verision > .NET 4.5 IEnumerable items = containerGenerator.GetPropertyValue("Items") as IEnumerable; if (items != null) { foreach (var childItem in items) { var parent = containerGenerator.ContainerFromItem(childItem) as EnhancedTreeViewItem; if (parent == null) { continue; } container = parent.ItemContainerGenerator.ContainerFromItem(item) as EnhancedTreeViewItem; if (container != null) { return container; } container = ContainerFromItem(parent.ItemContainerGenerator, item); if (container != null) { return container; } } } } return null; }
/// <summary> /// Method which generates the focus trail cell /// if it is not already generated and adds it to /// the block lists appropriately. /// </summary> private bool GenerateChildForFocusTrail( ItemContainerGenerator generator, List<int> realizedColumnIndices, List<int> realizedColumnDisplayIndices, Size constraint, int displayIndex, ref int displayIndexListIterator) { DataGrid dataGrid = ParentDataGrid; DataGridColumn column = dataGrid.ColumnFromDisplayIndex(displayIndex); if (column.IsVisible) { int columnIndex = dataGrid.ColumnIndexFromDisplayIndex(displayIndex); UIElement child = generator.ContainerFromIndex(columnIndex) as UIElement; if (child == null) { int childIndex = columnIndex; Size childSize; using (((IItemContainerGenerator)generator).StartAt(IndexToGeneratorPositionForStart(generator, childIndex, out childIndex), GeneratorDirection.Forward, true)) { child = GenerateChild(generator, constraint, column, ref childIndex, out childSize); } } if (child != null && DataGridHelper.TreeHasFocusAndTabStop(child)) { AddToIndicesListIfNeeded( realizedColumnIndices, realizedColumnDisplayIndices, columnIndex, displayIndex, ref displayIndexListIterator); return true; } } return false; }
protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled) { var key = e.Key; if (FlowDirection == FlowDirection.RightToLeft) { if (key == Key.Left) { key = Key.Right; } else if (key == Key.Right) { key = Key.Left; } } e.Handled = true; switch (key) { case Key.Escape: IsDropDownOpen = false; break; case Key.Enter: case Key.Space: if (IsDropDownOpen && FocusedIndex != SelectedIndex) { SelectedIndex = FocusedIndex; IsDropDownOpen = false; } else { IsDropDownOpen = true; } break; case Key.Right: case Key.Down: if (IsDropDownOpen) { if (FocusedIndex < Items.Count - 1) { FocusedIndex++; ((Control)ItemContainerGenerator.ContainerFromIndex(FocusedIndex)).Focus(); } } else { SelectedIndex = Math.Min(SelectedIndex + 1, Items.Count - 1); } break; case Key.Left: case Key.Up: if (IsDropDownOpen) { if (FocusedIndex > 0) { FocusedIndex--; ((Control)ItemContainerGenerator.ContainerFromIndex(FocusedIndex)).Focus(); } } else if (SelectedIndex != -1) { SelectedIndex = Math.Max(SelectedIndex - 1, 0); } break; default: e.Handled = false; break; } } else { Console.WriteLine("Already handled"); } }
/// <summary> /// Creates a new instance used to queue action for completion or items changes of <see cref="ItemContainerGenerator"/> /// </summary> /// <param name="generator">The <see cref="ItemContainerGenerator"/> to be used.</param> /// <param name="action">The <see cref="System.Action"/> that should be invoked.</param> public ItemContainerGeneratorAction(ItemContainerGenerator generator, Action action) { this.Generator = generator; this.Action = action; }
void UpdateDisplayedItem(object selectedItem) { object content; // Can't do anything with no content presenter if (_contentPresenter == null) { return; } // Return the currently displayed object (which is a UIElement) // to its original container. if (DisplayedItem != null) { content = _contentPresenter.Content; DisplayedItem.Content = content; DisplayedItem = null; } _contentPresenter.Content = null; if (selectedItem == null) { _contentPresenter.Content = NothingSelectedFallback; _contentPresenter.ContentTemplate = null; SelectionBoxItem = null; SelectionBoxItemTemplate = null; return; } // If the currently selected item is a ComboBoxItem (not ListBoxItem!), we // display its Content instead of the CBI itself. content = selectedItem; if (content is ComboBoxItem) { content = ((ComboBoxItem)content).Content; } // Only allow DisplayedItem to be non-null if we physically move // its content. This will only happen if DisplayedItem == SelectedItem DisplayedItem = ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as ComboBoxItem; SelectionBoxItem = content; SelectionBoxItemTemplate = ItemTemplate; // If displayed item is avaiable, we can get the right template from there. Otherwise // we need to create a container, read the template and destroy it. if (DisplayedItem != null) { SelectionBoxItemTemplate = DisplayedItem.ContentTemplate; if (content is UIElement) { DisplayedItem.Content = null; } else { DisplayedItem = null; } } else { bool fresh; ComboBoxItem container = ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as ComboBoxItem; if (container == null) { var index = ItemContainerGenerator.GeneratorPositionFromIndex(SelectedIndex); using (ItemContainerGenerator.StartAt(index, GeneratorDirection.Forward, true)) container = ItemContainerGenerator.GenerateNext(out fresh) as ComboBoxItem; ItemContainerGenerator.PrepareItemContainer(container); } SelectionBoxItemTemplate = container.ContentTemplate; } _contentPresenter.Content = SelectionBoxItem; _contentPresenter.ContentTemplate = SelectionBoxItemTemplate; }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ internal Generator(ItemContainerGenerator factory, GeneratorPosition position, GeneratorDirection direction, bool allowStartAtRealizedItem) { _factory = factory; _direction = direction; _factory.MapChanged += new MapChangedHandler(OnMapChanged); _factory.MoveToPosition(position, direction, allowStartAtRealizedItem, ref _cachedState); _done = (_factory.ItemsInternal.Count == 0); _factory.SetStatus(GeneratorStatus.GeneratingContainers); }
/// <summary> /// Initializes a new instance of the TreeView class. /// </summary> public TreeView() { DefaultStyleKey = typeof(TreeView); ItemContainerGenerator = new ItemContainerGenerator(this); }
public void SetGenerator(ItemContainerGenerator generator) { this.Generator = generator; generator.ItemsChanged += new ItemsChangedEventHandler(OnItemsChanged); }
private static TreeViewItem FindTreeViewItem(ItemContainerGenerator itemContainerGenerator, object dataContext) { if (itemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return null; if (itemContainerGenerator.Items.Contains(dataContext)) return (TreeViewItem)itemContainerGenerator.ContainerFromItem(dataContext); foreach (object item in itemContainerGenerator.Items) { TreeViewItem treeViewItem = (TreeViewItem)itemContainerGenerator.ContainerFromItem(item); TreeViewItem retVal = FindTreeViewItem(treeViewItem.ItemContainerGenerator, dataContext); if (retVal != null) return retVal; } return null; }
/// <summary> /// Called by ListBoxItem instances when they get focus /// </summary> /// <param name="listBoxItemNewFocus">ListBoxItem that got focus</param> internal override void NotifyListItemGotFocus(ListBoxItem listBoxItemNewFocus) { // Track the focused index _focusedIndex = ItemContainerGenerator.IndexFromContainer(listBoxItemNewFocus); }
protected override void OnKeyDown(KeyEventArgs e) { if (!e.Handled) { bool handled = false; int newFocusedIndex = -1; switch (e.Key) { case Key.Space: case Key.Enter: if ((Key.Enter != e.Key) || KeyboardNavigation.GetAcceptsReturn(this)) { if (ModifierKeys.Alt != (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Alt))) { // KeyEventArgs.OriginalSource (used by WPF) isn't available in Silverlight; use FocusManager.GetFocusedElement instead ListBoxItem listBoxItem = FocusManager.GetFocusedElement() as ListBoxItem; if (null != listBoxItem) { if ((ModifierKeys.Control == (Keyboard.Modifiers & ModifierKeys.Control)) && listBoxItem.IsSelected) { SelectedItem = null; } else { SelectedItem = ItemContainerGenerator.ItemFromContainer(listBoxItem); } handled = true; } } } break; case Key.Home: newFocusedIndex = 0; break; case Key.End: newFocusedIndex = Items.Count - 1; break; case Key.PageUp: newFocusedIndex = NavigateByPage(false); break; case Key.PageDown: newFocusedIndex = NavigateByPage(true); break; case Key.Left: if (IsVerticalOrientation()) { ElementScrollViewerScrollInDirection(Key.Left); } else { newFocusedIndex = _focusedIndex - 1; } break; case Key.Up: if (IsVerticalOrientation()) { newFocusedIndex = _focusedIndex - 1; } else { ElementScrollViewerScrollInDirection(Key.Up); } break; case Key.Right: if (IsVerticalOrientation()) { ElementScrollViewerScrollInDirection(Key.Right); } else { newFocusedIndex = _focusedIndex + 1; } break; case Key.Down: if (IsVerticalOrientation()) { newFocusedIndex = _focusedIndex + 1; } else { ElementScrollViewerScrollInDirection(Key.Down); } break; // case Key.Divide: // Feature only used by SelectionMode.Extended // case Key.Oem2: // Key not supported by Silverlight // break; // case Key.Oem5: // Key not supported by Silverlight // break; default: Debug.Assert(!handled); break; } if ((-1 != newFocusedIndex) && (-1 != _focusedIndex) && (newFocusedIndex != _focusedIndex) && (0 <= newFocusedIndex) && (newFocusedIndex < Items.Count)) { // A key press will change the focused ListBoxItem ListBoxItem listBoxItem = (ListBoxItem)ItemContainerGenerator.ContainerFromIndex(newFocusedIndex); Debug.Assert(null != listBoxItem); ScrollIntoView(ItemContainerGenerator.ItemFromContainer(listBoxItem)); if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { listBoxItem.Focus(); } else { SelectedItem = ItemContainerGenerator.ItemFromContainer(listBoxItem); } handled = true; } if (handled) { e.Handled = true; } } }