通过XAML实现WPF TreeView绑定

3

所以我有这样的类结构

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

因此,有4个对象:Store、Person(所有者和收银员)、Product和Vendor。

我希望找到一种将这个结构绑定到XAML树中的方法,以便每个节点表示该结构的一个对象,如下所示:

image 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

所以这里的重要区别在于,第一棵树的子节点是三种不同类型的对象(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; }
}

我希望避免在代码端创建树形结构。非常感谢您的帮助。

1个回答

2
我发现了一篇很棒的文章在WPF TreeView上组织异构数据,使用MultiBinding将不同的集合和对象结合在一起,并使用MultiValueConverter“塑造”项目树来解决此问题。它解决了我很多的问题,但仍在调整风格以适应我的口味。
希望这会有所帮助。

好的,这看起来正是我所需要的。我会回复你的。谢谢! - Carlo
终于有时间测试了,完美运作,谢谢! - Carlo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接