3

所以我有一个这样的类结构

Store
    Owner
    Cashier
    List of Products
        Product Name
        Price
    List of Vendors
        Company Name
        Contact Name

所以有 4 个对象:Store、Person(Owner 和 Cashier)、Product 和 Vendor。

我想找到一种方法将此结构绑定到 XAML 树中,因此每个节点都代表此结构的一个对象,例如:

图片 http://img23.imageshack.us/img23/9337/treexq.png

到目前为止,我只能使用一个顶级对象 -> 一个子对象来做到这一点。像这样:

Store
   - Departmen 1 Products
       Book 1
       Book 2
       Book 3
   - Department 2 Products
       Bike 1
       Bike 2
       Bike 3

所以这里的重要区别在于,在第一棵树中,子节点是 3 种不同类型的对象(Store 有 2 个 Person 对象,1 个 Product 和 1 个 Vendor 对象);而在第二种情况下,每个根节点只有一种类型的子节点(Store 有 Department,Department 有 Products)。

我已经使用 HierarchicalDataTemplates 完成了第二个示例,所以我认为这可以解决我的问题,但事实并非如此。关于我如何做到这一点的任何想法?下面是创建 Store 结构的代码:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        this.DataContext = new List<Store>() { Store.CreateStore() };
    }
}

public class Store
{
    public string StoreName { get; set; }
    public Person Owner { get; set; }
    public Person Cashier { get; set; }
    public List<Product> Products { get; set; }
    public List<Vendor> Vendors { get; set; }

    public Store()
    {
        this.Products = new List<Product>();
        this.Vendors = new List<Vendor>();
    }

    public static Store CreateStore()
    {
        Store store = new Store();

        // set name
        store.StoreName = "Book store";

        // set staff
        store.Owner = new Person() { FirstName = "John", LastName = "Smith" };
        store.Cashier = new Person() { FirstName = "Jane", LastName = "Smart" };

        // add products
        store.Products.Add(new Product() { Name = "Mechanical Pencil", Price = 1.25m});
        store.Products.Add(new Product() { Name = "Pen", Price = 2.50m });
        store.Products.Add(new Product() { Name = "WPF Book", Price = 28.94m });
        store.Products.Add(new Product() { Name = "ASP.NET Book", Price = 29.50m });

        // add vendors
        store.Vendors.Add(new Vendor() { CompanyName = "Bic", ContactName = "Bill Gates" });
        store.Vendors.Add(new Vendor() { CompanyName = "O'Reilly", ContactName = "Steve Jobs" });

        return store;
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Vendor
{
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
}

我想避免在代码端创建树结构。任何帮助将不胜感激。

4

1 回答 1

2

我发现了一篇很棒的文章在 WPF TreeView 上组织异构数据,它使用 MultiBinding 将不同的集合和对象组合在一起,并使用 MultiValueConverter 来“塑造”项目树,从而解决了这个问题。解决了我的很多问题,但仍在努力根据我的口味设计它。

希望这可以帮助

于 2009-11-06T01:57:42.773 回答