generic.xaml中的数据模板如何自动应用?

Thi*_*uda 5 c# wpf xaml custom-controls datatemplate

我有一个自定义控件,它有一个ContentPresenter,它将内容设置为任意对象.此对象对其类型没有任何约束,因此我希望此控件基于应用程序或Generic.xaml中定义的数据模板定义的任何数据模板显示其内容.如果在应用程序中我定义了一些数据模板(没有键,因为我希望它自动应用于该类型的对象),并且我使用绑定到该类型对象的自定义控件,数据模板将自动应用.但我在generic.xaml中为某些类型定义了一些数据模板,我在其中定义了自定义控件样式,并且这些模板未自动应用.这是generic.xaml:

<DataTemplate DataType="{x:Type PredefinedType>
    <!-- template definition -->
<DataTemplate>

<Style TargetType="{x:Type CustomControl}">
    <!-- control style -->
</Style>
Run Code Online (Sandbox Code Playgroud)

如果我将"PredefinedType"类型的对象设置为contentpresenter中的内容,则不会应用数据模板.但是,如果我在app.xaml中为使用自定义控件的应用程序定义数据模板,则它可以正常工作.

有人有线索吗?我真的不能假设控件的用户将定义这个数据模板,所以我需要一些方法来将它与自定义控件联系起来.

Joh*_*wen 5

仅在Generic.xaml中声明的资源被应用到控件的模板直接引用(通常由StaticResource引用)时,才将它们引入。在这种情况下,您无法设置直接引用,因此需要使用另一种方法将DataTemplates与ControlTemplate打包在一起。您可以通过将它们包括在更本地的Resources集合中来实现,例如ControlTemplate.Resources:

<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyControl}">
                <ControlTemplate.Resources>
                    <DataTemplate DataType="{x:Type local:MyDataObject}">
                        <TextBlock Text="{Binding Name}"/>
                    </DataTemplate>
                </ControlTemplate.Resources>
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)