4

When I am creating a Resource we are specifying the DataType inside it:

<Window.Resources> <DataTemplate x:Key="StudentView" DataType="this:StudentData"> <TextBox Text="{Binding Path=StudentFirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="2" VerticalAlignment="Center" /> <TextBox Text="{Binding Path=StudentGradePointAverage}" Grid.Row="2" Grid.Column="2" VerticalAlignment="Center" /> </DataTemplate> <Window.Resources> 

And while binding :

<ItemsControl ItemsSource="{Binding TheStudents}" ItemTemplate="{StaticResource StudentView}"> 

So why are we using the DataType, even if I remove the DatType , my sample runs fine. Is it restricting certain types , that can be inside DataTemplete?

But I tried binding one of the TextBox with a garbage value (Not present in the View-Model) and it works fine!

1
  • One advantage is that knowing the expected data context type allows for some static verification of whether binding paths are valid. It's also a documentation hint to future developers of the intention of the DataTemplate. Commented Jul 11, 2012 at 14:24

1 Answer 1

12

The DataType is for implicit application, if you drop the x:Key you do not need to reference it in the ItemsControl.ItemTemplate for example. Read the documentation.

This property that is very similar to the TargetType property of the Style class. When you set this property to the data type without specifying an x:Key, the DataTemplate gets applied automatically to data objects of that type. Note that when you do that the x:Key is set implicitly. Therefore, if you assign this DataTemplate an x:Key value, you are overriding the implicit x:Key and the DataTemplate would not be applied automatically.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.