How to move Content Control DataTemplate to Dictionary Resources XML
I've been given a great example of how to apply a dynamic style within a Conten Control.
I know my XA开发者_如何学JAVAML for each style is going to get really big, I'd like to split the DataTemplate off to separate XAML files (I guess ResourceDictionary's). I just can't seem to get it to work.
<ContentControl Content="{Binding MyViewModel}">
<ContentControl.Resources>
<DataTemplate x:Key="DefaultTemplate">
<TextBlock Text="DefaultTemplate" />
</DataTemplate>
<DataTemplate x:Key="TemplateA">
<TextBlock Text="Template A" />
</DataTemplate>
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
</ContentControl.Resources>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedView}" Value="ViewA">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
</DataTrigger>
<DataTrigger Binding="{Binding SelectedView}" Value="ViewB">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
As an example, I want this template:
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
to reside in a different XAML file (lets call it Test.xaml).
I've tried creating a ResourceDictionary file and referencing the Key in the DataTemplate, but obviously it couldn't find the key because it resides in a different XAML file, so I've tried to implement a Merged ResourceDictionary but VS2010 throws errors - e.g.
Test.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
with:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Test.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
But then I get an error "Resources Property has already been set".
What am I doing wrong?
Ben
精彩评论