开发者

Best way to bind DataGrid to generic list in WPF

开发者 https://www.devze.com 2023-01-28 12:30 出处:网络
I am trying to bind a DataGrid to a generic list in WPF. The following code results in blank rows for each row of data in my list (i.e. if i have 5 rows, it shows 5 rows, but doesn\'t shows any data

I am trying to bind a DataGrid to a generic list in WPF.

The following code results in blank rows for each row of data in my list (i.e. if i have 5 rows, it shows 5 rows, but doesn't shows any data in the cells):

List<DataRow>  DataBindingSource = GuestList.Where(row =>
  (row.Field<long>("FK_GROUP_ID") == Int64.Parse(cmbGroup.SelectedValue.ToString())) &&
  (row.Field<long>("FK_AGE_GROUP_ID") != (int)L_Age_Group.Child))
  .ToList();

gvwAddultDetails.ItemsSource = DataBindingSource;

If I convert my list of objects to a DataTable开发者_如何学运维, it works (shows data). For example:

List<DataRow> DataBindingSource = GuestList.Where(row =>
  (row.Field<long>("FK_GROUP_ID") == Int64.Parse(cmbGroup.SelectedValue.ToString())) &&
  (row.Field<long>("FK_AGE_GROUP_ID") != (int)L_Age_Group.Child))
  .ToList();

gvwAdultDetails.ItemsSource = DataBindingSource.CopyToDataTable().DefaultView;

But if I had a List<DataRow>, how would I convert it to DataTable?

What is the best practice for binding a DataGrid to a `List' in WPF?


One way to bind DataGrid to generic list in WPF:

MainWindow.xaml.cs

Grid.DataContext = DataBindingSource;

MainWindow.xaml

<DataGrid
  AutoGenerateColumns="True"
  ItemsSource="{Binding}"
  Name="Grid" />

But it probably won't work with DataRow, because in WPF, if you want to bind to something, it needs to be a property.

- OTHER THOUGHTS -

Here's how you can convert a generic list to a DataTable:

  • Generic List to DataTable

How to bind DataGrid to generic list in WPF:

  • Why isn't my WPF Datagrid showing data?

Especially (a great feature in WPF):

  • ObservableCollection<> WPF Example
0

精彩评论

暂无评论...
验证码 换一张
取 消