Conditional Data Templates in WPF

How would you select a different data file that adjusts to the field in the data binding source? I would have two different DataTemplates

<DataTemplate x:Key="DataTemplateLabel"> <Label Width="60" Height="25" Background="Red"> <TextBlock Text="{Binding Path=Name}"/> </Label> </DataTemplate> <DataTemplate x:Key="DataTemplateTxtBox"> <TextBox Width="60" Height="25" Background="Red" Text="{Binding Path=Text}"/> </DataTemplate> 

if (isText) Then use the DataTemplateTxtBox ELSE using the DataTemplateLabel) Is this possible? Thanks.

+6
wpf binding datatemplate
source share
2 answers

You can create a DataTemplateSelector and assign it to the ContentTemplateSelector property (or ItemTemplateSelector if it is in ItemsControl )

+7
source share

This is more of an indirect answer, but by performing polymorphism (i.e. leaving the IsText property and answering the question using a different type), you can define a DataTemplate for each other type.

0
source share

All Articles