Matt McManis
Matt McManis

Reputation: 4675

How to apply style to dynamic ComboBox Items?

I have a ComboBox with a Style set on TargetType ToggleButton

<ComboBox x:Name="comboBox1" Style="{StaticResource ComboBoxBlue}" HorizontalAlignment="Left" Margin="10,128,0,0" VerticalAlignment="Top" Width="75" />

The Items are set dynamically with C# using a List Item Source

public static List<string> MyItemSource = new List<string>() 
{ 
    "Item 1", "Item 2", "Item 3", "Item 4" 
};

comboBox1.ItemsSource = MyItemSource;

Set Items Background Color (Globally)

<!-- ComboBox Blue Item -->
<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Blue" />
    <Setter Property="BorderBrush" Value="Blue" />
</Style>

But how do I set to an x:Key so it only applies to certain ComboBoxes?

<Style x:Key="ComboBoxBlueItem" TargetType="{x:Type ComboBoxItem}">

I can use ComboBox.ItemContainerStyle tag on each ComboBox, but then I have to set each one's style individually.

<ComboBox.ItemContainerStyle>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Background" Value="Blue" />
    </Style>
</ComboBox.ItemContainerStyle>

Upvotes: 0

Views: 1080

Answers (1)

Eric
Eric

Reputation: 1847

This will use the above style for each item in this combobox:

<ComboBox ItemContainerStyle="{StaticResource ComboBoxBlueItem}" />

Upvotes: 2

Related Questions