5

I want to use templated ComboBoxItems which consist of an Image and a Label. If I assign the template to a ComboBoxItem, can I somehow set the Source-Property of the Image? The goal is to use the same template for different ComboBoxItems but with different pictures in each Item.

I also thought about binding the Image.Source-Property in the Template, but this fails because the "parent" ComboBoxItem has of course no Source-Property I could bind to.

The code illustrates my problem:

    <Style x:Key="ComboBoxPictureItem" TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBoxItem">
                    <StackPanel Orientation="Horizontal">
                        <Image x:Name="StatusImage" />
                        <Label x:Name="StatusLabel" Content="Green"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <ComboBox>
        <ComboBoxItem Style="{StaticResource ResourceKey=ComboBoxPictureItem}"
-> sth. like:         StatusImage.Source="PathToMyImage.png"/>
    </ComboBox>

Thank you!

H.B.
  • 166,899
  • 29
  • 327
  • 400
schoola
  • 704
  • 6
  • 12

1 Answers1

2

You should use template bindings to expose internal properties, e.g. bind the Label's content to the ComboBoxItem's content:

<Label Content="{TemplateBinding Content}"/>

If you now set the Content outside it is transferred to the label, you can do the same for the image, you may run out of properties though so if you want to do things that way you could inherit from ComboBoxItem and create more properties.

Here i do not think you want to mess with control templates really, just use the ItemTemplate to specify how the items look.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • 1
    Using my own class which inherits from ComboBoxItem is a possible solution, I just thought there might be an easier way. Thank you for the hint with the ItemTemplate, this is much more what I want than using a complete new ControlTemplate. I'll propably use a DataTemplate for the items as shown here: http://msdn.microsoft.com/en-us/library/ms742521.aspx to solve the problem. – schoola Dec 07 '11 at 11:20