DataGrid在绑定到ObservableCollection <object> </object>时显示空行

时间:2012-09-04 20:52:39

标签: c# datagrid observablecollection

我有一个简单的DataGrid,我绑定到一个ObservableCollection,它在Grid中生成黑色小行,没有Data Visible。我正在使用ObservableCollection,因为我使用Reflection在RunTime中构建了集合。

我正在做这样的事情 XAML

   <DataGrid ItemsSource="{Binding Data}" />

C#

public ObservableCollection<object> Data
{ 
        get { return _Data; }
        set { 
            this._deals = value;
            this.NotifyPropertyChanged("Deals");
            }
 }
 public Run()
 {
        this.Data = CreateData(typeof(MyRecordClass))   //'MyRecordClass' needs to be passed at runtime
  }


public ObservableCollection<Object> CreateData(Type RecordType)
{
   ObservableCollection<Object> data = new ObservableCollection<object>();  
   var record = Activator.CreateInstance(RecordType);
    // Logic to load the record with Data 
   data.Add(record);
   return data;
}

有没有一种方法可以让DataGrid读取ObservableCollection而不指定ColumnNames或在CreateData函数中创建一个ObservableCollection对象?

1 个答案:

答案 0 :(得分:1)

您的收藏集应具有公共属性,因此datagrid可以将列绑定到它。 如果使用Object的集合类型而不是没有绑定的特性,那么将显示空行。

以下是您的示例:

public partial class MainWindow:Window     {         public ObservableCollection dataSource;

    public MainWindow()
    {
        InitializeComponent();

        this.dataSource = new ObservableCollection<SomeDataSource>();

        this.dataSource.Add(new SomeDataSource { Field = "123" });
        this.dataSource.Add(new SomeDataSource { Field = "1234" });
        this.dataSource.Add(new SomeDataSource { Field = "12345" });

        this.dataGrid1.ItemsSource = this.dataSource;
    }
}

public class SomeDataSource
{
    public string Field {get;set;}
}



 <DataGrid AutoGenerateColumns="False" Height="253" HorizontalAlignment="Left" Margin="27,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="448">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First" Binding="{Binding Path=Field, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            </DataGrid.Columns>
 </DataGrid>