XAML中controltemplate中元素的访问属性 [英] Access property of element in controltemplate in XAML

查看:102
本文介绍了XAML中controltemplate中元素的访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我还考虑过将Image.Source-Property绑定到模板中,但是失败是因为父级 ComboBoxItem当然没有我可以绑定的源属性。

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.

代码说明了我的问题:

    <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>

谢谢!

推荐答案

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

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}"/>

如果您现在将内容设置为转移到标签之外,则可以对图像,但是您可能会用尽属性,因此,如果您想以这种方式进行操作,可以从ComboBoxItem继承并创建更多属性。

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.

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

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

这篇关于XAML中controltemplate中元素的访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆