How to set combobox size to maximum width of its contents?
I have this ComboBox
<ComboBox ItemsSource="{Binding Path=Foo.Bars}"/>
Is it possible to set the size of the drop-down list to the width of its widest element?
For example, if the contents are:
John Doe
Jane Mary
Josh
The length will be equal to the length of Jane Mary.
In addition, in this case, the content is not expected after initialization.
What you can do is make a converter that returns the longest length of one property of your object. You can implement such a converter as follows:
public class LongestListObjectToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is IEnumerable<FooBar>)
{
IEnumerable<FooBar> list = (IEnumerable<FooBar>)value;
return list.Max(bar => bar.FullName.Length);
}
// Default value to return
return 100;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And then just bind the Width property of your ComboBox, specifying the list as a Path binding and your converter as a value converter.
<Window.Resources>
<conv:LongestListObjectToIntConverter x:Key=converter/>
</Windows.Resources>
...
<ComboBox ItemsSource="{Binding Path=Foo.Bars}" Width="{Binding Path=Foo.Bars, Converter={StaticResource converter}}"/>
, , ComboBox .
- , , , .
, . ValueConverters : http://www.wpftutorial.net/ValueConverters.html
public class ComboBoxToMaxItemWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double maxWidth = 0;
ComboBox cb = (ComboBox)value;
foreach (var item in cb.Items)
{
ComboBoxItem cbItem = (ComboBoxItem)cb.ItemContainerGenerator.ContainerFromItem(item);
if (cbItem.ActualWidth > maxWidth)
maxWidth = cbItem.ActualWidth;
}
return maxWidth;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
<ComboBox ItemsSource="{Binding Path=Foo.Bars}" Width={Binding RelativeSource={RelativeSource Self}, Converter={StaticResource comboBoxToMaxItemWidthConverter }/>
,
@ArsenMkrt: cbItem null - SL ( : https://connect.microsoft.com/VisualStudio/feedback/details/687691/silverlight-4-5-beta-combobox-itemcontainergenerator-methods-return-null-and-not-a-combboxitem). .
@YogWiN: combobox ( ItemsSource), ComboBoxItem, . .
, PrepareContainerForItemOverride ComboBox, , . , MeasureOverride ...
So, as far as I know, today you cannot do this with the ComboBox control.
DropDownWidth can be used to set the width of the code. Use the following links for reference.
http://www.codeproject.com/KB/combobox/ComboBoxAutoWidth.aspx
However, this will set the size for the dropdown only.