void AddItemsToPresenter(GeneratorPosition position, int count) { if (_presenter == null || _presenter._elementRoot == null || _presenter._elementRoot is VirtualizingPanel) { return; } Panel panel = _presenter._elementRoot; int newIndex = ItemContainerGenerator.IndexFromGeneratorPosition(position); using (var p = ItemContainerGenerator.StartAt(position, GeneratorDirection.Forward, true)) for (int i = 0; i < count; i++) { var item = Items [newIndex + i]; DependencyObject container = null; bool fresh; container = ItemContainerGenerator.GenerateNext(out fresh); ContentControl c = container as ContentControl; if (c != null) { c.ContentSetsParent = false; } FrameworkElement f = container as FrameworkElement; if (f != null && !(item is FrameworkElement)) { f.DataContext = item; } panel.Children.Insert(newIndex + i, (UIElement)container); ItemContainerGenerator.PrepareItemContainer(container); } }
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; }