Wpf 仅在某些视图上针对的DataTemplate

Wpf 仅在某些视图上针对的DataTemplate,wpf,datatemplate,Wpf,Datatemplate,我在全局/共享资源字典中有一个DataTemplate,它以数据类型为目标: <DataTemplate DataType="{x:Type foo:Bar}"> <!-- My DataTemplate visual tree goes here... --> </DataTemplate> 此数据模板将替换所有视图(UserControls/Windows)上的所有foo:Bar类型。我要做的是将此模板仅应用于某些视图,使其他视图不受此Dat

我在全局/共享资源字典中有一个DataTemplate,它以数据类型为目标:

<DataTemplate DataType="{x:Type foo:Bar}">
    <!-- My DataTemplate visual tree goes here... -->
</DataTemplate>


此数据模板将替换所有视图(UserControls/Windows)上的所有foo:Bar类型。我要做的是将此模板仅应用于某些视图,使其他视图不受此DataTemplate的影响。我可以将此DataTemplate复制到每个视图的参考资料部分,但我不想复制/粘贴DataTemplate的内容,这会导致维护方面的麻烦。

您在这里使用的称为。你要求的是明确的。要实现这一点,可以使用显式资源密钥:

<DataTemplate x:Key="MyStyle" DataType="{x:Type foo:Bar}">
    <!-- My DataTemplate visual tree goes here... -->
</DataTemplate>

稍后在xaml中:

<ContentPresenter ContentTemplate="{StaticResource MyStyle}" .../>

另一个解决方案是通过适当的控件/页面内部使用一个资源字典(带有隐式数据模板)


我更喜欢第一种方法,因为它更容易维护(隐式样式更难跟踪)。

谢谢!第二种方法对我有效。我不能使用第一种方法,因为我没有创建foo:Bar类型的控件,它们是我隐式瞄准的第三方控件内部类型。