How will data templates in generic.xaml be applied automatically?

I have a custom control that has a ContentPresenter that will have an arbitrary object defined as content. This object has no restrictions on its type, so I want this control to display its contents based on any data patterns defined by the application or data patterns defined in Generic.xaml. If in the application I define some data template (without a key, because I want it to be automatically applied to objects of this type), and I use a custom control bound to an object of this type, the data template is applied automatically. But I have some data patterns defined for some types in generic.xaml where I define a user control style and these patterns are not applied automatically. Here is a generic .xaml:

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

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

If I set an object of type "PredefinedType" as content in the contentpresenter, the data template is not applied. However, if it works, if I define a data template in app.xaml for an application that uses a custom control.

Anyone got it? I really cannot assume that the user of the control will define this data template, so I need to somehow associate it with the user control.

+5
source share
1 answer

, Generic.xaml, , , ( StaticResource). , DataTemplates ControlTemplate. , , 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>
+4

All Articles