13

我正在使用 Linq To Sql 用 Segment 对象填充列表框,其中 Segment 是设计器创建/ORM 生成的类。

<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;

这行得通。

但是,如果我使用类型化数据模板(通过将 x:Key 替换为模板上的 DataType 属性,所有项目都显示为ICTemplates.Segment(ToString() 返回值)
,其概念是它应该自动拾取数据模板,如果类型匹配。有人可以在这里发现错误吗?

4

2 回答 2

33

泽错在这里

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

应该

<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}">
于 2008-12-16T17:21:53.640 回答
0

这只是一个猜测,但可能是因为上下文设置为 IQueryable 吗?如果将 DataContext 设置为 Segment 的单个实例,是否会得到相同的结果?

于 2008-12-16T16:43:05.217 回答