【问题标题】:Nested Collection Binding嵌套集合绑定
【发布时间】:2009-08-20 10:52:39
【问题描述】:

我想将嵌套集合绑定到网格面板,但不确定我可以如何动态地做到这一点。

这是我的收藏:

Public class GrandParent
{
    string name;
    Icollection<Parent> ParentCollection;
}

Public class Parent
{
    string lastname;
    Icollection<Child> ChildCollection;
}

Public class Child
{
    string name;
    int age;
}

我想要这样的输出:

GrandParent.Name Parent1.LastName Parent2.LastName Parent3.LastName

GP1 孩子[GP1,Parent1.LastName] 孩子[GP1,Parent2.LastName] 孩子[GP1,Parent3.LastName]
GP2 孩子[GP2,Parent1.LastName] 孩子[GP2,Parent2.LastName] 孩子[GP2,Parent3.LastName]

Parent.LastNames 是静态的。

截至目前,我的viewmodel类(绑定类)是这样的:

Class viewmodel
{
    collection<string> GrandParentNames
    {
    }

    collection<string> Parent1LastNames
    {
    }

    collection<string> Parent2LastNames
    {
    }

    collection<string> Parent3LastName
    {
    }
}

有人可以建议我更好的方法吗?

【问题讨论】:

  • 无论你想达到什么目标,我认为你走错路了......你打算用这些收藏做什么?

标签: wpf binding


【解决方案1】:

你的问题有点含糊;我不明白您要绑定的确切内容...您的意思是:

将嵌套集合绑定到网格面板

我可以马上告诉你,当使用嵌套的数据集合时,你最好的选择总是使用HierarchicalDataTemplate。这里有一个coupleexamples 的使用方法。

【讨论】:

    【解决方案2】:

    嘿,查理,看来我的问题没有很好地提出......对不起,同样的......

    我的集合是嵌套的,但我想要的输出不是嵌套的..

    应该是……

    我想用于标题名称的父属性 我想用于第一列的 GranParent 名称 而我想用于其他列的子属性

    所以输入是 Grant Parent -> Parent -> Child (1 to many)

    输出是

                 --         Parent        --               Parent1
    

    GrandParent.Name -- 父级的子级 -- Parent1 的子级 GrandParent1.Name -- 父级的子级 -- Parent1 的子级

    如果我在这里举个例子......

    国家 -> 职务 -> 人(姓名、年龄)

    例如美国 - 经理 - 人(A, 26) 美国 - 首席架构师 - 人 (B, 28) 英国 - 经理 - 人(C, 26) 英国 - 首席架构师 - Person (D, 28)

    **out put is :**
    

    (标题)

    国家 --- Mangaer --- 首席架构师

    (R0w1)


    美国 --- A, 26 --- B, 28

    (R0w2)

    英国 --- C,26 --- D, 28

    感谢任何线索或代码...

    【讨论】:

      【解决方案3】:

      我只是根据你的名字来假设你在 wpf 中这样做。

      在您的代码中,您对模型有正确的想法,但是(假设我理解您的目标)您在 ViewModel 上有点误入歧途。因为 GrandParent 类有一个父母的集合,而父母有一个孩子的集合,所以在您的 ViewModel 中,您只需要 ViewModel 中的 GrandParrent 集合。因此您的 ViewModel 将更接近:

      class ViewModel
          {
              ICollection<GrandParent> Grents;
          }
      

      正如您的视图一样,我所知道的最简单的方法是通过数据模板。你必须在你的网格中使用一个列表框,但是你可以根据你想要的结果来格式化列表框,这是 WPF 的荣耀。无论如何,我在这里做了一个简单的例子:

      <Window.Resources>
      
       <local:ViewModel x:Key="ViewModelDataSource" d:IsDataSource="True"/>
       <DataTemplate x:Key="GrandParents_Data_Template">
        <StackPanel>
      <TextBlock Text="{Binding name}"/>
      <ListBox ItemsSource="{Binding ParentCollection}" ItemTemplate="{DynamicResource Parents_Data_Template}"/>
      

      </Window.Resources>
      

      希望至少可以帮助您朝着正确的方向前进。如果您还有其他问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-09
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        • 2016-08-03
        • 1970-01-01
        相关资源
        最近更新 更多