WPF - ItemsControl / ListBox的可重用DataTemplate

时间:2015-07-03 06:10:53

标签: c# wpf listbox datatemplate itemscontrol

我需要重用以下DataTemplate:

        <DataTemplate x:Key="courseItemTemplate">
        <Border BorderThickness="3" CornerRadius="5">
            <Border.Background>
                <SolidColorBrush>
                    <SolidColorBrush.Color>
                        <MultiBinding Converter="{StaticResource CourseColorConverter}">
                            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="DataContext.CourseColors"/>
                            <Binding Path="Course.CourseInfo.ID"/>
                        </MultiBinding>
                    </SolidColorBrush.Color>
                </SolidColorBrush>
            </Border.Background>
            <ContentControl Content="{Binding}"/>
        </Border>
    </DataTemplate>

模板将同时为ListBox和ItemsControl提供不同的ItemsSource,以及用于呈现每个项目内容的不同模板。 基本上,我想要的是能够用每个控件的相关模板替换ContentControl标签

1 个答案:

答案 0 :(得分:0)

使用两个具有共同边框样式的DataTemplate:

<Style x:Key="BorderStyle" TargetType="Border">
    <Setter Property="Background">
        <Setter.Value>
            <SolidColorBrush>...</SolidColorBrush>
        </Setter.Value>
    </Setter>
</Style>
<DataTemplate x:Key="T1">
    <Border Style="{StaticResource BorderStyle}">
        <ContentPresenter Content="{Binding P1}"/>
    </Border>
</DataTemplate>
<DataTemplate x:Key="T2">
    <Border Style="{StaticResource BorderStyle}">
        <ContentPresenter Content="{Binding P2}"/>
    </Border>
</DataTemplate>