绑定到DataTemplate中的模板属性

时间:2011-07-29 00:15:06

标签: silverlight binding datatemplate controltemplate

我有一个自定义控件如下:

<CustomControl>
    <CustomControl.ContentTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>                    
        </DataTemplate>
    </CustomControl.ContentTemplate>
</CustomControl>

在CustomControl的控件模板中,我尝试从DataTemplate中绑定到CustomControl.ContentTemplate,但它不起作用:

<ListBox
ItemsSource="{Binding SearchResultsList}">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Vertical">
            <ContentControl
                Content="{Binding}"
                ContentTemplate="{TemplateBinding ContentTemplate}">
            </ContentControl>
            <ItemsControl
                ItemsSource="{Binding HierarchyPath}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="->"/>
                            <TextBlock Text="{Binding Name}"/>
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

注意: ContentTemplate =“{TemplateBinding ContentTemplate}”

我知道你不能在Datatemplate中使用TemplateBinding,即使DataTemplate在控件模板中。但有没有人知道如何在不使用TemplateBinding的情况下实现我想要实现的目标?

1 个答案:

答案 0 :(得分:0)

您最好的选择是使用ListBox.ItemContainerStyle,并使用它来制作ControlTemplate。

这样的事情:

<ListBox>
<ListBox.ItemContainerStyle>
    <Style  TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <StackPanel Orientation="Vertical">
                        <ContentControl
                            Content="{Binding}"
                            ContentTemplate="{TemplateBinding ContentTemplate}">
                        </ContentControl>
                        <ItemsControl
                            ItemsSource="{Binding HierarchyPath}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="->"/>
                                        <TextBlock Text="{Binding Name}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>
</ListBox>