user1647334
user1647334

Reputation: 13

DataGrid Showing Blank Lines when bound to an ObservableCollection<Object>

I have a simple DataGrid which I am binding to a ObservableCollection and its producing black small lines in the Grid with no Data Visible. I am using ObservableCollection as I have the collection being built in RunTime using Reflection.

I am doing something like this 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;
}

Is there a way in which I can make the DataGrid read an ObservableCollection without specifying the ColumnNames or create a ObservableCollection object in the CreateData function ?

Upvotes: 1

Views: 1299

Answers (1)

Vitaliy Nesterenko
Vitaliy Nesterenko

Reputation: 358

Your collection should have public properties, so datagrid could bind columns to it. If you use collection type of Object than you have no properies for binding, so the empty rows will be displayed.

Here is example for you:

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>

Upvotes: 1

Related Questions