Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property of element in controltemplate in XAML

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!

like image 559
schoola Avatar asked Nov 04 '22 09:11

schoola


1 Answers

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.

like image 178
H.B. Avatar answered Nov 11 '22 06:11

H.B.