XAML 中控制模板中元素的访问属性

sch*_*ola 5 wpf xaml wpf-controls controltemplate

我想使用由图像和标签组成的模板化 ComboBoxItems。如果我将模板分配给 ComboBoxItem,我可以以某种方式设置图像的源属性吗?目标是为不同的 ComboBoxItems 使用相同的模板,但在每个 Item 中使用不同的图片。

我还考虑过在模板中绑定 Image.Source-Property,但这失败了,因为“父”ComboBoxItem 当然没有我可以绑定的 Source-Property。

代码说明了我的问题:

    <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>
Run Code Online (Sandbox Code Playgroud)

谢谢!

H.B*_*.B. 3

您应该使用模板绑定来公开内部属性,例如将 Label 的内容绑定到 ComboBoxItem 的内容:

<Label Content="{TemplateBinding Content}"/>
Run Code Online (Sandbox Code Playgroud)

如果您现在将外部内容设置为传输到标签,您可以对图像执行相同的操作,但您可能会用完属性,因此如果您想要以这种方式执行操作,您可以从 ComboBoxItem 继承并创建更多属性。

在这里,我认为您不想真正弄乱控件模板,只需使用ItemTemplate来指定项目的外观即可。