I have a List which contains different types of objects:
List
<Window x:Class="MiscSamples.DataTemplates"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="DataTemplates"
Height="300"
Width="300">
<Window.Resources>
<!-- DataTemplate for strings -->
<DataTemplate DataType="{x:Type sys:String}">
<TextBox Text="{Binding Path=.}" />
</DataTemplate>
<!-- DataTemplate for DateTimes -->
<DataTemplate DataType="{x:Type sys:DateTime}">
<DataTemplate.Resources>
<DataTemplate DataType="{x:Type sys:String}">
<TextBlock Text="{Binding Path=.}" />
</DataTemplate>
</DataTemplate.Resources>
<DatePicker SelectedDate="{Binding Path=.}" />
</DataTemplate>
<!-- DataTemplate for Int32 -->
<DataTemplate DataType="{x:Type sys:Int32}">
<Slider Maximum="100"
Minimum="0"
Value="{Binding Path=.}"
Width="100" />
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource="{Binding}" />
</Window>
Code Behind:
public partial class DataTemplates : Window
{
public DataTemplates()
{
InitializeComponent();
var myList = new List<object>();
myList.Add(DateTime.Now);
myList.Add(50);
myList.Add("Hello World");
DataContext = myList;
}
}
Result:
As you can see, there's no reason at all to use code to manipulate UI elements in WPF (except some very very specific cases)
Edit:
Note that you don't usually create a DataTemplate
for classes inside the System
namespace (such as System.String
. This is only to give you an example. If you really needed this you would probably have to create a ViewModel
for each type.