I found a strange behavior when using ComboBox with enum items. I noticed that the popup that displays the entries when I click on the ComboBox truncates long items. I figured out that this happens because I define a TextBlock style with a fixed Width. What is strange is that, the Width only affects the ComboBox when I use enum items. It does not happen If I use string ones instead.
Here's a picture with what's going on. The third item should be "VeryLongTypeName".
Here is the code sample written according with the MVVM pattern.
The UserControl XAML:
<UserControl.DataContext>
<local:SampleViewModel/>
</UserControl.DataContext>
<StackPanel>
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="Width" Value="70"/>
<Setter Property="Margin" Value="0,0,5,0"/>
</Style>
</StackPanel.Resources>
<DockPanel>
<TextBlock Text="Items"/>
<ComboBox ItemsSource="{Binding ItemsList}" SelectedItem="{Binding Item}"/>
</DockPanel>
<DockPanel>
<TextBlock Text="String Items"/>
<ComboBox ItemsSource="{Binding StringItemsList}" SelectedItem="{Binding StringItem}"/>
</DockPanel>
</StackPanel>
The SampleViewModel code:
public class SampleViewModel
{
public enum SomeType { Type1, Type2, VeryLongTypeName };
public IEnumerable<SomeType> ItemsList
{
get { return (SomeType[])Enum.GetValues(typeof(SomeType)); }
}
public SomeType Item { get { return ItemsList.First(); } set { } }
public IEnumerable<string> StringItemsList
{
get { return ItemsList.Select(type => type.ToString()); }
}
public string StringItem { get { return StringItemsList.First(); } set { } }
}
If you build the code sample, in the second ComboBox below the one from the picture, things go smoothly with string values.
I have the following questions:
Why does changing the type affect the graphics?
How do I fix the ComboBox display when using enum?
Any help is welcomed.
TextBlock
as well? Because that looks like the same width. Don't know much about WPF, but maybe you shouldn't apply your style in such a global manner. – NyergudsStringItem = StringItemsList[0];
in your constructor is the proper way to do it. – user1228