c# – Josh Smith MVVM演示应用

在MainWindow,我们有:
<HeaderedContentControl 
          Content="{Binding Path=Workspaces}"
          ContentTemplate="{StaticResource Workspacestemplate}"
          Header="Workspaces"
          Style="{StaticResource MainHCCStyle}"
          />

在资源中:

<DataTemplate x:Key="Workspacestemplate">
    <TabControl 
      IsSynchronizedWithCurrentItem="True" 
      ItemsSource="{Binding}" 
      ItemTemplate="{StaticResource ClosableTabItemTemplate}"
      Margin="4"
      />
  </DataTemplate>

文章中说:

A typed DataTemplate does not have an x:Key value assigned to it,but
it does have its DataType property set to an instance of the Type
class. If WPF tries to render one of your viewmodel objects,it will
check to see if the resource system has a typed DataTemplate in scope
whose DataType is the same as (or a base class of) the type of your
viewmodel object
. If it finds one,it uses that template to render the
viewmodel object referenced by the tab item’s Content property.

我的问题是:

模板如何知道类型是工作空间的集合(Workspaceviewmodel)?

解决方法

在您发布的代码中,它不需要.在您的示例中,您已为内容模板赋予了严格的值:您已明确使用{StaticResource Workspacestemplate},因此查找了具有“Workspacestemplate”键的资源.

因为你已经明确地设置了模板,所以预期的类型是什么并不重要:它会尝试使用你设置的模板在你的内容显示任何对象 – 如果你使用的类型不同,会有不同程度的成功不匹配!

在您提到的替代方法中 – 使用“类型化DataTemplate”,您将使用< DataTemplate DataType =“{x:Type l:WorkSpace}”/>声明您的datatemplate.请注意,没有x:Key(并且我假设您有一个映射到本地代码的命名空间).这里发生的是WPF自动将资源的密钥设置为DataType(重要的是要注意:资源密钥不必是字符串!).

然后,当您声明HeaderedContentControl时,可以省略设置ContentTemplate.在运行时,当呈现控件时,WPF将检查Content对象的类型并发现它是WorkSpace,然后它将使用x:Key =“{x:Type l:WorkSpace}”查找资源“ – 这将匹配您键入的模板.

这是在整个应用程序中对数据进行一致表示的有用方法,因为类型化的DataTemplate将在整个应用程序中由任何内容呈现控件自动使用.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...