如何以编程方式将行插入Silverlight DataGrid而不进行绑定?

时间:2010-06-07 22:04:56

标签: silverlight datagrid silverlight-4.0

我使用常见的Silverlight DataGrid来显示搜索结果。搜索的“架构”可能因查询而异。

为了适应这种情况,我试图动态填充DataGrid。我可以设置显式设置列,但我在设置ItemSource时遇到问题。所有MSDN示例都将ItemSource设置为具有强类型的集合(例如,具有与架构匹配的公共属性的自定义类型)。然后,DataGrid使用反射来搜索与列匹配的公共属性的强类型。

由于我的搜索结果是动态的,因此我无法创建强类型来表示返回的内容。我可以不只是给DataGrid任意对象列表,只要每个列表中的对象数量与列数相匹配即可吗?有人知道这是否可行?

我想做类似的事情:

List<List<object>> myResults = <voodoo that populates the result list>

myDataGrid.ItemsSource = myResults;

3 个答案:

答案 0 :(得分:1)

以下文章让我接近我想要的东西: http://blogs.msdn.com/b/scmorris/archive/2008/04/14/defining-silverlight-datagrid-columns-at-runtime.aspx

基本上,您必须具有可绑定属性。您不能只根据任意项目列表创建行。我偶然发现了几个解决这个问题的开源项目,它们使用反射在运行时构建CLR类型,然后绑定到这些类型。

答案 1 :(得分:1)

Colin Eberhardt已经发布了一个巧妙的解决方案来解决你所描述的问题 -

http://www.scottlogic.co.uk/blog/colin/2010/03/binding-a-silverlight-3-datagrid-to-dynamic-data-via-idictionary-updated/

答案 2 :(得分:0)

是的,有可能。这是从MSDN刷过的样本     使用系统;     使用System.Collections.Generic;     使用System.Windows.Controls;

namespace DataGridSnippets
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            // Set the ItemsSource to autogenerate the columns.
            dataGrid1.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid3.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid4.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid5.ItemsSource = Customer.GetSampleCustomerList();
        }
    } 

    public class Customer
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Address { get; set; }
        public Boolean IsNew { get; set; }

        // A null value for IsSubscribed can indicate 
        // "no preference" or "no response".
        public Boolean? IsSubscribed { get; set; }

        public Customer(String firstName, String lastName, 
            String address, Boolean isNew, Boolean? isSubscribed)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Address = address;
            this.IsNew = isNew; 
            this.IsSubscribed = isSubscribed;
        }

        public static List<Customer> GetSampleCustomerList()
        {
            return new List<Customer>(new Customer[4] {
                new Customer("A.", "Zero", 
                    "12 North Third Street, Apartment 45", 
                    false, true), 
                new Customer("B.", "One", 
                    "34 West Fifth Street, Apartment 67", 
                    false, false),
                new Customer("C.", "Two", 
                    "56 East Seventh Street, Apartment 89", 
                    true, null),
                new Customer("D.", "Three", 
                    "78 South Ninth Street, Apartment 10", 
                    true, true)
            });
        }
    }
}