加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Josh Smith MVVM演示应用

发布时间:2020-12-15 08:18:21 所属栏目:百科 来源:网络整理
导读:在MainWindow,我们有: HeaderedContentControl Content="{Binding Path=Workspaces}" ContentTemplate="{StaticResource WorkspacesTemplate}" Header="Workspaces" Style="{StaticResource MainHCCStyle}" / 在资源中: DataTemplate x:Key="WorkspacesTem
在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将在整个应用程序中由任何内容呈现控件自动使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读