【问题标题】:How to create two HierarchicalDataTemplates which are mutually-referential in Silverlight?如何在 Silverlight 中创建两个相互引用的 HierarchicalDataTemplate?
【发布时间】:2010-09-27 15:47:00
【问题描述】:

鉴于:

  1. TargetType 无法分配 DataTemplates
  2. StaticResource 引用只能引用以前

如何在 TreeView 中对以下情况进行模板化?

class Resource {
  public string Name {get;}
  public IEnumerable<Property> Properties {get;}
}

class Property {
  public string Name {get;}
  public IEnumerable<Resource> Values {get;}
}

这种结构很适合一棵看起来像这样的树:

Resource 1
|- Property A
   | - Resource 2
   | - Resource 3
|- Property B
   |- Resource 4

由于HierarchicalDataTemplateTargetType 属性,这对于WPF 中的模板来说是微不足道的。在 Silverlight 中,我们必须做一些类似的事情:

<HierarchicalDataTemplate x:Key="ResourceTemplate"
                          ItemSource="{Binding Properties}"
                          ItemTemplate={StaticResource PropertyTemplate}" />

<HierarchicalDataTemplate x:Key="PropertyTemplate"
                          ItemSource="{Binding Values}"
                          ItemTemplate="{StaticResource ResourceTemplate}" />

这显然行不通,因为 ResourceTemplate 不能引用 PropertyTemplate,因为它是在 XAML 文档中定义的。那么,如何解决这个先有鸡还是先有蛋的问题呢?

【问题讨论】:

    标签: silverlight xaml resourcedictionary hierarchicaldatatemplate


    【解决方案1】:

    我找到的唯一合理的解决方案是创建第三种 ViewModel 类型,它将包装前两种类型(资源或属性)中的任何一种,并提供要绑定到的通用属性:(例如子级)。但是,如果这两种类型需要非常不同的模板,这仍然不是很理想,因为那时我正在使用VisualStateManager 在数据模板之间切换。

    <HierarchicalDataTemplate x:Key="TreeItemTemplate"
                              ItemSource="{Binding Children}">
      <ContentPresenter Content="{Binding}">
        <VisualStateManager.Groups>
          <VisualStateGroup>
            <VisualState Name="IsResource">
              <!-- set resource template -->
            </VisualState>
            <VisualState Name="IsProperty">
              <!-- set property template -->
            </VisualState>
          </VisualStateGroup>
        </VisualStateManager.Groups>
      </ContentPresenter>
    </HierarchicalDataTemplate>
    

    【讨论】:

    • 请注意,这并不能真正回答我试图提出的问题,即两个资源如何相互引用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2011-06-25
    • 2016-08-13
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多