Search code examples
c#wpfvalue-typeitemssourcereference-type

Controls with a collection use the incorrect styling with value types


Controls with collections in WPF (e.g. ListBox or ComboBox) use TextBlock styling instead of their own when using value types (like int or enum).

Verifiable example:

Xaml code:

<Window.Resources>
    <Style TargetType="ComboBox">
        <Setter Property="FontSize" Value="8"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="Green" />
    </Style>

    <Style TargetType="TextBlock">
        <Setter Property="FontSize" Value="50"/>
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <ComboBox Name="cbb1" Margin="0 -100 0 0"/>
    <ComboBox Name="cbb2"/>
</Grid>

CS code:

//In the constructor
cbb1.ItemsSource = new[] { "A", "B", "C" };
cbb1.SelectedItem = cbb1.Items[0];

cbb2.ItemsSource = new[] { 1, 2, 3 };
cbb2.SelectedItem = cbb2.Items[0];

This example code will show 2 ComboBox's, one where the items have the 'incorrect' TextBlock styling and the other will have the 'normal' ComboBox styling.

Other then making a class for needed value types (most commonly enums for me) or removing the style is there a workaround or fix for this?


Solution

  • Declare an ItemTemplate with a TextBlock, which does not use the default TextBlock Style:

    <Style TargetType="ComboBox">
        <Setter Property="FontSize" Value="8"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>