views:

212

answers:

1

I have a custom control that has a ContentPresenter that will have an arbitrary object set as it content. This object does not have any constraint on its type, so I want this control to display its content based on any data templates defined by application or by data templates defined in Generic.xaml. If in a application I define some data template(without a key because I want it to be applied automatically to objects of that type) and I use the custom control bound to an object of that type, the data template gets applied automatically. But I have some data templates defined for some types in the generic.xaml where I define the custom control style, and these templates are not getting applied automatically. Here is the 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 the content in the contentpresenter, the data template does not get applied. However, If it works if I define the data template in the app.xaml for the application thats using the custom control.

Does someone got a clue? I really cant assume that the user of the control will define this data template, so I need some way to tie it up with the custom control.

A: 

Resources declared in Generic.xaml are only pulled in if they are directly referenced by the template being applied to a control (usually by a StaticResource reference). In this case you can't set up a direct reference so you need to use another method to package the DataTemplates with your ControlTemplate. You can do this by including them in a more local Resources collection, like 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>
John Bowen
Worked nicely, thanks :)
Thiado de Arruda