c# - Josh Smith MVVM 演示应用程序

标签 c# mvvm datatemplate

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)?

最佳答案

它不需要,在您发布的代码中。在您的示例中,您已经为内容模板赋予了严格的值(value):您已明确使用 {StaticResource WorkspacesTemplate} ,所以资源的键为 "WorkspacesTemplate被查找。

因为您已经显式设置了模板,所以预期的类型是什么并不重要:它会尝试显示您的 Content 中的任何对象。使用您设置的模板 - 如果您使用不匹配的类型,会获得不同程度的成功!

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

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

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

关于c# - Josh Smith MVVM 演示应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16979028/

相关文章:

C#时区计算问题

javascript - 一个具有多个模板的 VueJS 组件

android - 如何使用 Kodein 为工厂类实例化许多参数

c# - 从 ListBox 中的数据对象获取 DataTemplate

c# - 以编程方式将 TextBlock 添加到 DataTemplate

c# - System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

c# - 返回具有不同泛型类型的泛型接口(interface)实现

c# - ASP.NET MVC 2 中具有一个名称的多个 Controller

c# - WPF。 mvvm 中的快捷方式

wpf - DataTemplate 和 ItemTemplate 的数据错误 26