How can data templates in generic.xaml get applied automatically?

两盒软妹~` 提交于 2019-12-07 04:28:00

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/2751707/how-can-data-templates-in-generic-xaml-get-applied-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!