Textbox or Datepicker in DataTemplate. Based on the data type I want one, but not both
I have a datatemplate for my listbox:
<DataTemplate x:Key="CheckBoxTextBoxItemTemplate">
<StackPanel Orientation="Horizontal">
<CheckBox Focusable="False" IsChecked="{Binding IsChecked}" VerticalAlignment="Center"/>
<ContentPresenter Content="{Binding Name, Mode=OneTime}" Margin="2,0" Width="140"开发者_如何学运维 VerticalAlignment="Center"/>
<TextBox Text="{Binding FieldData}" Margin="2,0" Width="200" Visibility="{Binding FieldDataVisible}"/>
</StackPanel>
</DataTemplate>
However the items in the list that the listbox is bound to are not all String types. Some are DateTime and a few are Integers. I would like to have a datetimepicker displayed instead of a textbox for the DateTime types. How can I make this happen.
To clarify some points the list is populated at runtime using reflection so I don't know which fields are what types ahead of time.
Within the Resources block of the ListBox, you could specify a DataTemplate for each type (pseudocode):
<ListBox.Resources>
<DataTemplate DataType="{x:Type String}">
<TextBlock />
</DataTemplate>
<DataTemplate DataType="{x:Type DateTime}">
<DateTimePicker />
</DataTemplate>
</ListBox.Resources>
Note that you don't refer to these template by an identifier; they will simply be applied to any instance of the specified DataType in their scope (the ListBox).
Alternatively, you can implement a DataTemplateSelector to return a different template for each type.
精彩评论