Darf Zon Darf Zon - 4 months ago 22
C# Question

How to show a data template on a content control?

Imagine that in one data template, I have a textBox, and another data template, I've got two textboxes.

According to this, in the view has a checkbox, and show each template.. is this possible?

Sorry if my question is so doubt, I've investigate it but I didn't find out.

I was did this, I know this is useless, but is only for testing.

<Window x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="350" Width="525">

<DataTemplate DataType="{x:Type ContentControl}" x:Key="T1">
<TextBox Height="20" />
<DataTemplate DataType="{x:Type ContentControl}" x:Key="T2">
<TextBox Height="20" />
<TextBox Height="20" />

<ContentControl Template="{StaticResource T1}" />


Your design should include a template selector...

DataTemplates are an extremely powerful part of WPF, and by using them, you can abstract all sorts of display code. However, there are times when they fall short - and initially when I was learning WPF I was disappointed by that. For instance, you only get to set one DataTemplate on an items control, and while that made sense, it felt limiting. What if I wanted to use different templates depending on the content of the item? Do I have to build all that logic into a single data template?

source: Switch on the code

This is WPF's answer to your question and should produce the behaviour you are after. The tutorial has some lucid examples to show the technique...

Note: Alternate link at WPF Tutorial - How to use a Data Template Selector