// Calculates and applies the minimum width necessary to accommodate the tabs in the // specified tab control private void adjustColumnMinWidth() { if (AssociatedObject == null || TabControl == null || Column < 0 || Column >= AssociatedObject.ColumnDefinitions.Count || TabControl.Items.Count == 0) { return; } ColumnDefinition cDef = AssociatedObject.ColumnDefinitions[Column]; // Difference between column width and tab control width. This difference needs to be // preserved when calculating the new column width. double tabControlMargin = cDef.ActualWidth - TabControl.ActualWidth; double aggregateTabWidths = 0; double tabPanelMargin = 0; // Calculate width for each tab for (int i = 0; i < TabControl.Items.Count; i++) { TabItem tab = TabControl.Items[i] as TabItem; if (tab == null) { return; // Unexpected object type - bail out } double threshholdWidth = double.IsNaN(tab.MinWidth) ? 0 : tab.MinWidth; if (tab.ActualWidth > threshholdWidth) { // Aggregate tab width and margin aggregateTabWidths += tab.ActualWidth + tab.Margin.Left + tab.Margin.Right; if (i == 0) { // Get the margin of the panel containing the tabs. Note that this is the only // dimension on an element external to the tabs that is taken into account, so // if the TabControl's template has been modified to include other elements, this // measurement will not be sufficient. TabPanel tabPanel = tab.FindAncestorOfType <TabPanel>(); if (tabPanel != null) { tabPanelMargin += tabPanel.Margin.Left + tabPanel.Margin.Right; } } } else { return; // nothing to measure - bail out } } // Apply calculated widths as column min width. The constant 2 is applied as this is necessary // to prevent wrapping, but walking the visual tree and measuring could not account for these // 2 pixels cDef.MinWidth = tabControlMargin + tabPanelMargin + aggregateTabWidths + 2; }