Search code examples
xamldatatemplateitemtemplate

WPF: Apply the same ItemTemplate to multiple comboboxes


In my application, I created a DataTemplate for a ComboBox. (See the XAML below.) I want to apply this style to multiple ComboBoxes in the application. How can I do this?

<ComboBox Name="mouseColorCmbx" AutomationProperties.AutomationId="SimulationOptionsPanel_mouseColorCmbx" Grid.Column="1" Grid.Row="0" Margin="0 0 0 0" HorizontalAlignment="Stretch" VerticalAlignment="Center">
            <ComboBox.ItemTemplate>
                <DataTemplate DataType="Forms:ColorInfo">
                    <StackPanel Orientation="Horizontal" Margin="0,3,0,0">
                        <Border Margin="2,0,2,0" BorderThickness="1">
                            <Border.BorderBrush>
                                <SolidColorBrush Color="Black"/>
                            </Border.BorderBrush>
                            <Border.Background>
                                <SolidColorBrush Color="{Binding Path=Color}"/>
                            </Border.Background>
                            <Rectangle Height="10" Width="25"/>
                        </Border>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

Solution

  • You should use application resources. Adding your own style(template) to global resource allow you share it with multiple controls.