Conditional Data Templates in WPF
Asked Answered
H

2

6

How would it be possible to choose a different datatemplate accroding the a field in the data binding source? I would have 2 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 DataTemplateTxtBox ELSE use DataTemplateLabel) Is this possible? Thanks.

Handyman answered 21/10, 2009 at 12:36 Comment(0)
L
7

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

Larue answered 21/10, 2009 at 13:1 Comment(0)
L
0

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

Loth answered 21/10, 2009 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.