You cannot do this directly in Xaml, but you can use this Attached Behavior. (The width will be visible in the Designer)
<ComboBox behaviors:ComboBoxWidthFromItemsBehavior.ComboBoxWidthFromItems="True"> <ComboBoxItem Content="Short"/> <ComboBoxItem Content="Medium Long"/> <ComboBoxItem Content="Min"/> </ComboBox>
Attached Behavior ComboBoxWidthFromItemsProperty
public static class ComboBoxWidthFromItemsBehavior { public static readonly DependencyProperty ComboBoxWidthFromItemsProperty = DependencyProperty.RegisterAttached ( "ComboBoxWidthFromItems", typeof(bool), typeof(ComboBoxWidthFromItemsBehavior), new UIPropertyMetadata(false, OnComboBoxWidthFromItemsPropertyChanged) ); public static bool GetComboBoxWidthFromItems(DependencyObject obj) { return (bool)obj.GetValue(ComboBoxWidthFromItemsProperty); } public static void SetComboBoxWidthFromItems(DependencyObject obj, bool value) { obj.SetValue(ComboBoxWidthFromItemsProperty, value); } private static void OnComboBoxWidthFromItemsPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e) { ComboBox comboBox = dpo as ComboBox; if (comboBox != null) { if ((bool)e.NewValue == true) { comboBox.Loaded += OnComboBoxLoaded; } else { comboBox.Loaded -= OnComboBoxLoaded; } } } private static void OnComboBoxLoaded(object sender, RoutedEventArgs e) { ComboBox comboBox = sender as ComboBox; Action action = () => { comboBox.SetWidthFromItems(); }; comboBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle); } }
What he does is that he calls the extension method for the ComboBox, called SetWidthFromItems, which (invisibly) expands and collapses itself, and then calculates the width based on the generated ComboBoxItems. (IExpandCollapseProvider requires a link to UIAutomationProvider.dll)
Then the extension method SetWidthFromItems
public static class ComboBoxExtensionMethods { public static void SetWidthFromItems(this ComboBox comboBox) { double comboBoxWidth = 19;
This extension method also provides the ability to call
comboBox.SetWidthFromItems();
in the code behind (for example, in the ComboBox.Loaded event)
Fredrik Hedblad Dec 11 2018-10-12T00: 00Z
source share