Why is my typed data template not being applied?
Asked Answered
C

2

14

I'm using Linq To Sql to fill up a listbox with Segment objects, where Segment is designer created/ORM generated class.

<Window x:Class="ICTemplates.Window1"
    ...
    xmlns:local="clr-namespace:ICTemplates"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
      <DataTemplate x:Key="MyTemplate"> 
      <!--  <DataTemplate DataType="x:Type local:Segment"> -->
        // some stuff in here
      </DataTemplate>
    </Window.Resources>
    <ListView x:Name="tvwSegments" ItemsSource="{Binding}" ItemTemplate="{StaticResource MyTemplate}" MaxHeight="200"/>


// code-behind
var queryResults = from segment in tblSegments
                               where segment.id <= iTemplateSid
                               select segment;
tvwSegments.DataContext = queryResults;

This works.

However if I used a Typed Data Template (by replacing the x:Key with the DataType attribute on the template, the items all show up with ICTemplates.Segment (the ToString() return value)
The concept is that it should pick up the data template automatically if the Type matches. Can someone spot the mistake here?

Choppy answered 16/12, 2008 at 9:52 Comment(0)
C
35

Ze Mistake is here

<DataTemplate DataType="x:Type local:Segment">  <!-- doesn't work -->

should be

<DataTemplate DataType="{x:Type local:Segment}">

Came home... made a toy-sample and it worked with this change. Gotta try that @ work tomorrow. Sheesh.. for want of 2 curlies..

Update: Found out another gotcha

<DataTemplate x:Key="SegTemplate" DataType="{x:Type local:Segment}">  <!-- doesn't work -->

won't work. Seems like you can have it either with a Key OR DataType attribute. To make this typed data template work.. had to remove the Key attribute and now it works as expected. Behavior is consistent for a HierarchicalDataTemplate too.

<DataTemplate DataType="{x:Type local:Segment}">
Choppy answered 16/12, 2008 at 17:21 Comment(2)
According to the docs, x:Key overrides the implicit (auto-generated) type-dependent key. The template keeps working, but you have to declare it explicitly in the object.Dekaliter
Shame on you, Microsoft.Blackman
T
0

This is just a guess, but could it be because the context is set to an IQueryable? If you set the DataContext to a single instance of a Segment, do you get the same result?

Traction answered 16/12, 2008 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.