@Fragilerus and @Liz, in fact, I think I came up with something better. Here is another approach that not only avoids the additional ContentPresenter binding, but also eliminates the need to use a template in a template, since shared content is direct content that is installed at compile time. The only thing that happens at runtime is the bindings that you set inside the direct content. Thus, it greatly speeds up the user interface compared to another solution.
<Border x:Shared="False" x:Key="Foo" BorderBrush="Red" BorderThickness="1" CornerRadius="4"> <TextBlock Text="{Binding SomeProp}" /> </Border> <DataTemplate x:Key="TemplateA"> <ContentPresenter Content="{StaticResource Foo}" /> </DataTemplate> <DataTemplate x:Key="TemplateB"> <ContentPresenter Content="{StaticResource Foo}" /> </DataTemplate>
Important. Be sure to use the x:Shared attribute in your shared content, otherwise this will not work.
WPF'y Way
From the above, this is really not the most convenient way for WPF to do what you need. This can be achieved using the DataTemplateSelector class, which does just that ... choosing a data template based on any criteria you set.
For example, you can easily install one of them that searches for your known data types and returns the same DataTemplate for both of them, but for all other types it returns to the system to resolve the DataTemplate. This is what we are actually doing here.
Hope this helps! :)
MarqueIV May 7 '11 at 8:46 am 2011-05-07 08:46
source share