public void Adding_To_Logical_Tree_Should_Reevaluate_DataTemplates()
        {
            var root   = new TestRoot();
            var target = new ContentPresenter();

            target.Content = "Foo";
            Assert.Null(target.Child);

            root.Child = target;
            target.ApplyTemplate();
            Assert.IsType <TextBlock>(target.Child);

            root.Child = null;
            root       = new TestRoot
            {
                DataTemplates =
                {
                    new FuncDataTemplate <string>((x, _) => new Decorator()),
                },
            };

            root.Child = target;
            target.ApplyTemplate();
            Assert.IsType <Decorator>(target.Child);
        }
Beispiel #2
0
        public void Clearing_Content_Should_Remove_From_LogicalChildren()
        {
            var target = new ContentPresenter();
            var child  = new Control();

            target.Content = child;
            target.ApplyTemplate();
            target.Content = null;
            target.ApplyTemplate();

            Assert.Equal(new ILogical[0], ((ILogical)target).LogicalChildren.ToList());
        }
Beispiel #3
0
        public void Clearing_Content_Clear_Childs_Parent()
        {
            var target = new ContentPresenter();
            var child  = new Control();

            target.Content = child;
            target.ApplyTemplate();
            target.Content = null;
            target.ApplyTemplate();

            Assert.Null(child.Parent);
            Assert.Null(child.GetLogicalParent());
        }
Beispiel #4
0
        //

        private object FindItemControl(ItemsControl itemsControl, string controlName, object item)
        {
            ContentPresenter container = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter;

            container.ApplyTemplate();
            return(container.ContentTemplate.FindName(controlName, container));
        }
Beispiel #5
0
        public void Clearing_Content_Should_Fire_LogicalChildren_CollectionChanged()
        {
            var target = new ContentPresenter();
            var child  = new Control();
            var called = false;

            target.Content = child;
            target.ApplyTemplate();

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

            target.Content = null;
            target.ApplyTemplate();

            Assert.True(called);
        }
Beispiel #6
0
        protected virtual void OnContentChanged(object oldContent, object newContent)
        {
            this.StopPreviousVisual();
            Storyboard       enterStoryboard  = this.EnterStoryboard;
            ContentPresenter contentPresenter = new ContentPresenter();

            contentPresenter.Content         = newContent;
            contentPresenter.ContentTemplate = this.ContentTemplate;
            this.Children.Add((UIElement)contentPresenter);
            if (enterStoryboard == null)
            {
                return;
            }
            contentPresenter.ApplyTemplate();
            if (this.IsLoaded)
            {
                if (this.ContentTemplate != null)
                {
                    enterStoryboard.Begin((FrameworkElement)contentPresenter, (FrameworkTemplate)this.ContentTemplate);
                }
                else
                {
                    enterStoryboard.Begin((FrameworkElement)contentPresenter);
                }
            }
            this.toBeStopped = (FrameworkElement)contentPresenter;
        }
        public bool RefreshLocation()
        {
            bool result = true;

            //List<CQPin> pin_in = new List<CQPin>();
            //List<CQPin> pin_out = new List<CQPin>();
            for (int i = 0; i < this.itemscontrol_in.Items.Count; i++)
            {
                ContentPresenter container = this.itemscontrol_in.ItemContainerGenerator.ContainerFromIndex(i) as ContentPresenter;
                container.ApplyTemplate();
                FrameworkElement oo  = container.ContentTemplate.FindName("rectangle", container) as FrameworkElement;
                CQPin            pin = oo.DataContext as CQPin;
                this.GetPinLocation(pin, oo);
                //pin_in.Add(pin);
            }
            for (int i = 0; i < this.itemscontrol_out.Items.Count; i++)
            {
                ContentPresenter container = this.itemscontrol_out.ItemContainerGenerator.ContainerFromIndex(i) as ContentPresenter;
                container.ApplyTemplate();
                FrameworkElement oo  = container.ContentTemplate.FindName("rectangle", container) as FrameworkElement;
                CQPin            pin = oo.DataContext as CQPin;
                this.GetPinLocation(pin, oo);
                //pin_out.Add(pin);
            }
            if (this.OnGateMove != null)
            {
                this.OnGateMove(this);
            }
            return(result);
        }
Beispiel #8
0
        public void Setting_Content_Should_Make_Control_Appear_In_LogicalChildren()
        {
            var target = new ContentPresenter();
            var child  = new Control();

            target.Content = child;
            target.ApplyTemplate();

            Assert.Equal(new[] { child }, ((ILogical)target).LogicalChildren.ToList());
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="objectName"></param>
        /// <param name="callback"></param>
        protected void ExecuteForContentChild <T>(ContentPresenter parent, string objectName, Action <T> callback)
            where T : FrameworkElement
        {
            parent.ApplyTemplate();
            var obj = parent.ContentTemplate.FindName(objectName, parent) as T;

            if (obj != null)
            {
                callback(obj);
            }
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            bd = GetTemplateChild("SelectTen") as Border;


            ContentPresenter cp = GetTemplateChild("contentPresenter") as ContentPresenter;

            _EditContent = GetTemplateChild("contentPresenter1") as ContentPresenter;

            if (_column.IsNotNull() && _column.Formatter.IsNotNull())
            {
                var     _b      = BindingOperations.GetBinding(cp, ContentPresenter.ContentProperty);
                Binding newbind = new Binding {
                    Converter = _column.Formatter, Path = _b.Path, Mode = _b.Mode, RelativeSource = _b.RelativeSource
                };
                BindingOperations.ClearBinding(cp, ContentPresenter.ContentProperty);
                BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, newbind);
            }
            cp.ApplyTemplate();
            tb = WpfTreeHelper.FindChild <AyText>(cp);
            if (tb.IsNotNull())
            {
                tb.TextWrapping = CellTextWrapping;

                if (CellCharacterEllipsis == TextTrimming.CharacterEllipsis)
                {
                    ToolTip tt  = new System.Windows.Controls.ToolTip();
                    AyText  ttb = new AyText();
                    ttb.SetBinding(AyText.TextProperty, new Binding {
                        Source = cp.Content
                    });
                    tt.Content = ttb;
                    tb.ToolTip = tt;
                    if (dpd != null)
                    {
                        dpd.AddValueChanged(tb, ActualWidthPropertyChangedHandler);
                    }
                    if (tb.ActualWidth < tb.DesiredSize.Width)
                    {
                        tt.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        tt.Visibility = Visibility.Collapsed;
                    }
                }
                tb.TextTrimming = CellCharacterEllipsis;
            }
        }
        public void Setting_Content_To_Control_Should_Not_Set_Child_Unless_UpdateChild_Called()
        {
            var target = new ContentPresenter();
            var child  = new Border();

            target.Content = child;
            Assert.Null(target.Child);

            target.ApplyTemplate();
            Assert.Null(target.Child);

            target.UpdateChild();
            Assert.Equal(child, target.Child);
        }
        public void Setting_Content_To_String_Should_Not_Create_TextBlock_Unless_UpdateChild_Called()
        {
            var target = new ContentPresenter();

            target.Content = "Foo";
            Assert.Null(target.Child);

            target.ApplyTemplate();
            Assert.Null(target.Child);

            target.UpdateChild();
            Assert.IsType <TextBlock>(target.Child);
            Assert.Equal("Foo", ((TextBlock)target.Child).Text);
        }
        public void Setting_Content_To_Control_Should_Set_Child()
        {
            var target = new ContentPresenter();
            var child  = new Border();

            target.Content = child;

            // Child should not update until ApplyTemplate called.
            Assert.Null(target.Child);

            target.ApplyTemplate();

            Assert.Equal(child, target.Child);
        }
        public void Setting_Content_To_String_Should_Create_TextBlock()
        {
            var target = new ContentPresenter();

            target.Content = "Foo";

            // Child should not update until ApplyTemplate called.
            Assert.Null(target.Child);

            target.ApplyTemplate();

            Assert.IsType <TextBlock>(target.Child);
            Assert.Equal("Foo", ((TextBlock)target.Child).Text);
        }
        /// <summary>
        /// Sets shell content to specified <param name="data" /> and returns <see cref="INavigatableView"/> which has been created for content.
        /// </summary>
        /// <param name="data">Data to use for content.</param>
        /// <param name="navigationTargetType">Type of current navigation target.</param>
        /// <returns></returns>
        private INavigatableView SetContentAndGetNavigatable(object data, Type navigationTargetType)
        {
            NavigationTargetType = navigationTargetType;
            BeforeApplyTemplate(data);
            ContentPresenter.Content = data;
            ContentPresenter.ApplyTemplate();
            if (VisualTreeHelper.GetChildrenCount(ContentPresenter) == 1)
            {
                var rv = VisualTreeHelper.GetChild(ContentPresenter, 0);
                (rv as UIElement)?.Focus();
                return(rv as INavigatableView);
            }

            return(null);
        }
Beispiel #16
0
        public ItemsControlAdorner(Button adornedElement, AdornerLayer adornerLayer, object data, DataTemplate dataTemplate)
            : base(adornedElement)
        {
            if (_currentInstance != null)
            {
                _currentInstance.Hide(); // hides other adorners of the same type
            }
            if (_btn != null && _btn == adornedElement)
            {
                _currentInstance.Hide(); // hides the adorner of this button (toggle)
                _btn = null;
            }
            else
            {
                _adornerLayer = adornerLayer;
                _btn          = adornedElement;

                // adjust position if sizes change
                _adornerLayer.SizeChanged += (s, e) => { UpdatePosition(); };
                _btn.SizeChanged          += (s, e) => { UpdatePosition(); };

                _contentPresenter = new ContentPresenter()
                {
                    Content = data, ContentTemplate = dataTemplate
                };

                // apply template explicitly: http://stackoverflow.com/questions/5679648/why-would-this-contenttemplate-findname-throw-an-invalidoperationexception-on
                _contentPresenter.ApplyTemplate();

                // get close button from datatemplate
                Button closeBtn = _contentPresenter.ContentTemplate.FindName("PART_CloseButton", _contentPresenter) as Button;
                if (closeBtn != null)
                {
                    closeBtn.Click += (s, e) => { this.Hide(); _btn = null; }
                }
                ;

                _visualChildren = new VisualCollection(this); // this is needed for user interaction with the adorner layer
                _visualChildren.Add(_contentPresenter);

                _adornerLayer.Add(this);

                _currentInstance = this;

                UpdatePosition(); // position adorner
            }
        }
Beispiel #17
0
        public MultiButtonBarControl(BarMultiButton barItem) : base(barItem)
        {
            this.Buttons = this.BarItem.Buttons.Values.Select(b => new ButtonWrapper(this, b)).ToList();

            this.InitializeComponent();

            // Apply theming to the dynamic buttons when they're created.
            this.ButtonContainer.ItemContainerGenerator.StatusChanged += async(sender, args) =>
            {
                if (this.ButtonContainer.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
                {
                    foreach (ButtonWrapper b in this.ButtonContainer.ItemContainerGenerator.Items)
                    {
                        ContentPresenter content = (ContentPresenter)this.ButtonContainer.ItemContainerGenerator.ContainerFromItem(b);
                        content.ApplyTemplate();

                        if (content.ContentTemplate.FindName("ControlButton", content) is ButtonBase control)
                        {
                            await b.SetControlAsync(control);
                        }
                    }
                }
            };

            // Set the navigation modes, depending on its type.
            bool isPair = (this.BarItem.Type == MultiButtonType.Toggle ||
                           this.BarItem.Type == MultiButtonType.Additive);

#if CombinePairs
            // For keyboard navigation, paired buttons act as a single control
            this.Focusable = isPair;
            this.Panel.SetValue(FocusManager.IsFocusScopeProperty, isPair);
            this.Panel.SetValue(KeyboardNavigation.DirectionalNavigationProperty,
                                isPair ? KeyboardNavigationMode.None : KeyboardNavigationMode.Continue);
            this.Panel.SetValue(KeyboardNavigation.TabNavigationProperty,
                                isPair ? KeyboardNavigationMode.None : KeyboardNavigationMode.Continue);
#endif

            if (isPair)
            {
                this.KeyDown += this.OnKeyDown_ButtonPair;
            }
        }
        private void viewModel_EditModeEnter(object sender, EventArgs e)
        {
            this.grpBoxOptionGroup.ApplyTemplate();
            Border headborder = (Border)this.grpBoxOptionGroup.Template.FindName("Header", this.grpBoxOptionGroup);

            if (headborder != null)
            {
                ContentPresenter headContentPresenter = (ContentPresenter)headborder.Child;
                headContentPresenter.ApplyTemplate();
                var       dataTemplate    = this.grpBoxOptionGroup.HeaderTemplate;
                TextBlock headerTextBlock = dataTemplate.FindName("textBlockName", headContentPresenter) as TextBlock;
                TextBox   headerTextBox   = dataTemplate.FindName("textBoxName", headContentPresenter) as TextBox;
                headerTextBox.Text         = headerTextBlock.Text;
                headerTextBox.Visibility   = Visibility.Visible;
                headerTextBlock.Visibility = Visibility.Collapsed;
                headerTextBox.Focus();
                headerTextBox.SelectAll();
            }
        }
Beispiel #19
0
        private void UpdateBindings()
        {
            var template = IsEditing ? EditingElement : Element;

            contentPresenter.ContentTemplate = template;
            contentPresenter.ApplyTemplate();
            UpdateRootElement();

            if (CurrentRootElement != null)
            {
                var bindingTargetProperty = GetBindingTargetProperty(CurrentRootElement);
                var appliedBinding        = BindingUtils.CloneBinding(Binding);
                if (appliedBinding is Binding)
                {
                    ((Binding)appliedBinding).Mode = IsEditing ? BindingMode.TwoWay : BindingMode.OneWay;
                }
                BindingOperations.SetBinding(CurrentRootElement, bindingTargetProperty, appliedBinding);

                SetBindings(CurrentRootElement);
            }
        }
        /// <summary>
        /// Permet de cocher toutes les oeuvres présentes dans AjouterA
        /// </summary>
        public void CocherSélectionnées()
        {
            for (int i = 0; i < AAjouter.Count; i++)
            {
                ContentPresenter contentPresenter = (ContentPresenter)lItemsControl.ItemContainerGenerator.ContainerFromItem(AAjouter.ElementAt(i));

                //Si l'oeuvre n'est pas présente dans l'affichage, quand par exemple un certain type est sélectionné
                if (contentPresenter == null)
                {
                    return;
                }

                contentPresenter.ApplyTemplate();
                Button   leBouton = contentPresenter.ContentTemplate.FindName("leBoutonOeuvre", contentPresenter) as Button;
                PackIcon lIcone   = contentPresenter.ContentTemplate.FindName("lIcone", contentPresenter) as PackIcon;

                leBouton.BorderBrush = new SolidColorBrush(Color.FromRgb(43, 120, 228));
                lIcone.Kind          = PackIconKind.TickCircleOutline;
                lIcone.Foreground    = new SolidColorBrush(Color.FromRgb(43, 120, 228));
            }
        }
Beispiel #21
0
        private void OnClosing(object sender, CancelEventArgs e)
        {
            if (!IsResultOk)
            {
                return;
            }

            foreach (var item in IconsList.FindVisualChildren <FrameworkElement>().Where(x => x.Name == @"NewIcon"))
            {
                if (!(item.DataContext is AppWindowItem data) || !data.IsInEditMode)
                {
                    continue;
                }

                item.DataContext = data;
                data.Save();
                var size   = new Size(CommonAcConsts.AppIconWidth, CommonAcConsts.AppIconHeight);
                var result = new ContentPresenter {
                    Width = size.Width, Height = size.Height, Content = item
                };

                SaveIcon();
                data.ShowEnabled = !data.ShowEnabled;
                SaveIcon();

                void SaveIcon()
                {
                    result.Measure(size);
                    result.Arrange(new Rect(size));
                    result.ApplyTemplate();
                    result.UpdateLayout();

                    var bmp = new RenderTargetBitmap(CommonAcConsts.AppIconWidth, CommonAcConsts.AppIconHeight, 96, 96, PixelFormats.Pbgra32);

                    bmp.Render(result);
                    bmp.SaveTo(data.IconOriginal);
                    BetterImage.Refresh(data.IconOriginal);
                }
            }
        }
Beispiel #22
0
        public static void HighlightSelectedElement(Element newElement, VisualPeriodicTable vpt)
        {
            for (int i = 0; i < vpt.ElementGrid.Items.Count; i++)
            {
                ContentPresenter c =
                    (ContentPresenter)vpt.ElementGrid.ItemContainerGenerator.ContainerFromItem(
                        vpt.ElementGrid.Items[i]);
                c.ApplyTemplate();
                TextBlock tb             = c.ContentTemplate.FindName("ElementBlock", c) as TextBlock;
                var       currentElement = tb.Tag as Element;
                var       elementSquare  = c.ContentTemplate.FindName("ElementSquare", c) as Border;

                if (currentElement == newElement)
                {
                    elementSquare.BorderBrush = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    elementSquare.BorderBrush = null;
                }
            }
        }
Beispiel #23
0
        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            ItemsControl itemsControl = (ItemsControl)this.window.FindName("ButtonsControl");

            if (itemsControl.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
            {
                return;
            }
            foreach (MessageWindow.ChoiceCommand choiceCommand in (IEnumerable)itemsControl.Items)
            {
                ContentPresenter contentPresenter = (ContentPresenter)itemsControl.ItemContainerGenerator.ContainerFromItem((object)choiceCommand);
                contentPresenter.ApplyTemplate();
                if (VisualTreeHelper.GetChildrenCount((DependencyObject)contentPresenter) > 0)
                {
                    Button button = (Button)VisualTreeHelper.GetChild((DependencyObject)contentPresenter, 0);
                    if (button.IsDefault)
                    {
                        Keyboard.Focus((IInputElement)button);
                        break;
                    }
                }
            }
        }
Beispiel #24
0
        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            ItemsControl itemsControl = (ItemsControl)this.window.FindName("ButtonsControl");

            if (itemsControl.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                foreach (MessageWindow.ChoiceCommand item in (IEnumerable)itemsControl.Items)
                {
                    ContentPresenter contentPresenter = (ContentPresenter)itemsControl.ItemContainerGenerator.ContainerFromItem(item);
                    contentPresenter.ApplyTemplate();
                    if (VisualTreeHelper.GetChildrenCount(contentPresenter) <= 0)
                    {
                        continue;
                    }
                    Button child = (Button)VisualTreeHelper.GetChild(contentPresenter, 0);
                    if (!child.IsDefault)
                    {
                        continue;
                    }
                    Keyboard.Focus(child);
                    break;
                }
            }
        }
        private InlineUIContainer CreateTokenContainer(string inputText, object token)
        {
            // Note: we are not using the inputText here, but could be used in future

            var presenter = new ContentPresenter()
            {
                Content         = token,
                ContentTemplate = TokenTemplate,
            };

            presenter.ApplyTemplate();
            Button bt = TokenTemplate.FindName("btn_delCtc", presenter) as Button;

            bt.Click += bt_Click;

            InlineUIContainer inlin = new InlineUIContainer(presenter)
            {
                BaselineAlignment = BaselineAlignment.TextBottom
            };

            bt.Tag = inlin;
            // BaselineAlignment is needed to align with Run
            return(inlin);
        }
Beispiel #26
0
        private void Update()
        {
            ActivityList.Items.Clear();
            FormGrid.Children.Clear();

            SalesConn   sc = new SalesConn();
            RefundsConn rc = new RefundsConn();

            ProductsConn  pc = new ProductsConn();
            DiscountsConn dc = new DiscountsConn();

            List <Sale>   sales   = sc.List;
            List <Refund> refunds = rc.List;

            history.Clear();
            relationProd.Clear();
            relationDisc.Clear();

            selProd = null;
            selDisc = null;

            // Crear elementos.
            Sale     selSale;
            Product  selProduct;
            Discount selDiscount;

            // Recuperar todas las ventas.
            for (int j = 0; j < sales.Count; j++)
            {
                ContentPresenter conItem = new ContentPresenter();
                conItem.Content = sales[j].Id.ToString();

                conItem.ContentTemplate = (DataTemplate)Resources["SaleMenuItem"];

                int max = refunds.Count;

                // Si coincide con alguna devolución convertir elemento de menu en Return.
                for (int k = 0; k < max; k++)
                {
                    if (sales[j].Id == refunds[k].SaleId)
                    {
                        conItem.ContentTemplate = (DataTemplate)Resources["ReturnMenuItem"];
                    }
                }

                // Añadimos el elemento.
                ActivityList.Items.Add(conItem);

                // Obtener Sale, Product y Discount.
                selSale = sales[j];

                try
                {
                    selProduct = pc.Get(selSale.ProdId.Value);
                }
                catch
                {
                    selProduct = null;
                }

                try
                {
                    selDiscount = dc.Get(selSale.DiscId.Value);
                }
                catch
                {
                    selDiscount = null;
                }

                // Se crea su formulario
                ContentPresenter conForm = new ContentPresenter();
                conForm.IsEnabled       = false;
                conForm.ContentTemplate = (DataTemplate)Resources["SaleForm"];
                conForm.ApplyTemplate();

                // Obtener contenedor.
                DataTemplate auxDT = conForm.ContentTemplate;

                // Obtener elementos de la GUI
                StackPanel products  = (StackPanel)auxDT.FindName("Products", conForm);
                StackPanel discounts = (StackPanel)auxDT.FindName("Discounts", conForm);

                float paying = 0;
                // Agregar producto
                if (selSale.ProdId != null && selSale.ProdId != 0)
                {
                    ContentPresenter productItem = new ContentPresenter();
                    productItem.Content         = selSale.ProdId;
                    productItem.ContentTemplate = (DataTemplate)Resources["ProductItem"];

                    products.Children.Clear();
                    products.Children.Add(productItem);

                    Product tmpProduct = pc.Get(int.Parse(productItem.Content.ToString()));
                    paying = tmpProduct.ProdPrice;
                }

                float discounting = 0;
                // Agregar descuento
                if (selSale.DiscId != null && selSale.DiscId != 0)
                {
                    ContentPresenter discountItem = new ContentPresenter();
                    discountItem.Content         = selSale.DiscId;
                    discountItem.ContentTemplate = (DataTemplate)Resources["DiscountItem"];

                    discounts.Children.Clear();
                    discounts.Children.Add(discountItem);

                    Discount tmpDiscount = dc.Get(int.Parse(discountItem.Content.ToString()));
                    discounting = tmpDiscount.PricePerc;

                    (auxDT.FindName("Discounted", conForm) as TextBox).Text = discounting.ToString();
                }

                // INSERTAR TODOS LOS DATOS NUMERICOS

                float result = paying - (paying * discounting / 100);
                (auxDT.FindName("TotalCost", conForm) as TextBlock).Text = "Total: " + result + "€";

                // Dar de alta en History y Relations
                history.Add(conItem, conForm);
                relationProd.Add(conItem, selProduct);
                relationDisc.Add(conItem, selDiscount);
            }
        }
Beispiel #27
0
        private void items_SelectionChanged(object sender, SelectionChangedEventArgs <TabItem> e)
        {
            LoadTemplateItems();
            if (_internalAction)
            {
                return;
            }

            if (e.AddedItems.Count > 0)
            {
                // selection has changed
                TabItem newItem = e.AddedItems[0];

                if (ic != null)
                {
                    for (int i = 0; i < ic.Items.Count; i++)
                    {
                        // I really dislike this roundabout way that I have to get the child items of an ItemsControl, but I guess this is how it is
                        // from https://stackoverflow.com/a/1876534/2987285
                        ContentPresenter c = (ContentPresenter)ic.ItemContainerGenerator.ContainerFromItem(ic.Items[i]);
                        c.ApplyTemplate();
#if NETCOREAPP
                        TabDisplayItem?tb = c.ContentTemplate.FindName("PART_TabItem", c) as TabDisplayItem;
#else
                        TabDisplayItem tb = c.ContentTemplate.FindName("PART_TabItem", c) as TabDisplayItem;
#endif
                        if (tb != null)
                        {
                            if (tb.TabItem != null && tb.TabItem == newItem)
                            {
                                tb.IsSelected = true;
                            }
                            else
                            {
                                tb.IsSelected = false;
                            }
                        }
                    }
                }

                if (ch != null)
                {
                    ch.Child = newItem.Content;
                }
                TabChanged?.Invoke(this, new TabItemChangeEventArgs(newItem));
            }
            else
            {
                if (Items.SelectedItems.Count == 0)
                {
                    if (ch != null)
                    {
                        ch.Child = null;
                    }

                    if (Items.Count > 0)
                    {
                        switch (SelectedTabClosedAction)
                        {
                        case SelectedTabCloseAction.SelectNothing:
                            // nothing to do
                            break;

                        case SelectedTabCloseAction.SelectFirstTab:
                            Items.Select(Items[0]);
                            break;

                        case SelectedTabCloseAction.SelectLastTab:
                            Items.Select(Items[Items.Count - 1]);
                            break;

                        case SelectedTabCloseAction.SelectTabToLeft:
                            if (closedTabIndex == -1)
                            {
                                // most likely closed via Items.Remove command
                                Items.Select(Items[0]);
                            }
                            else if (closedTabIndex == 0)
                            {
                                // left most tab closed
                                Items.Select(Items[0]);
                            }
                            else
                            {
                                Items.Select(Items[closedTabIndex - 1]);
                            }
                            break;

                        case SelectedTabCloseAction.SelectTabToRight:
                            if (closedTabIndex == -1)
                            {
                                // most likely closed via Items.Remove command
                                Items.Select(Items[Items.Count - 1]);
                            }
                            else
                            {
                                Items.Select(Items[closedTabIndex]);
                            }
                            break;

                        default:
                            // treat as if SelectNothing
                            break;
                        }
                    }
                }
            }
        }
 internal Control GetRootControlFromContentPresenter(ContentPresenter container)
 {
     container.ApplyTemplate();
     return((Control)VisualTreeHelper.GetChild(container, 0));
 }