首页 文章

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

提问于
浏览
5

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

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

<Style TargetType="{x:Type CustomControl}">
    <!-- control style -->
</Style>

如果我将“PredefinedType”类型的对象设置为contentpresenter中的内容,则不会应用数据模板 . 但是,如果我在app.xaml中为使用自定义控件的应用程序定义数据模板,它是否有效 .

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

1 回答

  • 4

    Generic.xaml中声明的资源只有在应用于控件的模板(通常是StaticResource引用)直接引用时才会被引入 . 在这种情况下,您无法设置直接引用,因此您需要使用另一种方法将DataTemplate与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>
    

相关问题