Sharing DataTemplates between controls

时间:2018-02-03 08:14:35

标签: wpf templates resources

I have a ContentPresenter in a couple of places in my application with exactly the same DataTemplates. For now I simply copy-pasted them, but I'd like to clean that up and share them between ContentPresenter instances. I tried this approach:

<ContentControl Content="{Binding DataEditorViewModel}">
    <ContentControl.Resources>
        <ResourceDictionary Source="pack://application:,,,/LogAnalyzer;component/PredicateDataEditors.xaml" />
    </ContentControl.Resources>
</ContentControl>

Application runs, but DataTemplates aren't being applied, I simply see name of class being ContentPresenter's content instead of defined template. I put templates in ResourceDictionary in the following way:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:LogAnalyzer"
                xmlns:p="clr-namespace:LogAnalyzer.BusinessLogic.ViewModels.Processing;assembly=LogAnalyzer.BusinessLogic"
                xmlns:xwt="http://schemas.xceed.com/wpf/xaml/toolkit">
    <DataTemplate DataType="{x:Type p:MessageRuleDataEditorViewModel}" x:Key="{x:Type p:MessageRuleDataEditorViewModel}">
        (...)
    </DataTemplate>

    (...)

</ResourceDictionary>

What should I do to embed DataTemplates correctly in ContentPresenter's resources?

1 个答案:

答案 0 :(得分:1)

if you define this data template in your app.xaml:

 <DataTemplate DataType="{x:Type p:MessageRuleDataEditorViewModel}">
     <TextBlock Text="testing" />
 </DataTemplate>

and then do something like:

 <ListBox ItemsSource="{Binding MyCollectionOfMessageRuleDataEditorViewModels}"/>

then your data template is automatically applied to every object of that same type. dont define a key for your global templates