Mitu
Mitu

Reputation: 49

Binding Datatable to a datagrid in WPF

I have a view model in my C# 4.0 app which has a System.Data.DataTable that's created in it using a service call. I want to bind this to a datagrid in my XAML file.

I tried following line DataGrid_Loaded event but its getting fired up before my datatable gets created inside the view model.

xaml:

<dg:DataGrid Name="myDataGrid" Loaded="DataGrid_Loaded"/>

xaml.cs:

myDataGrid.ItemsSource = myViewModel.myDataTable.DefaultView;

Upvotes: 1

Views: 16748

Answers (1)

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

Check the following suggestion: In your code behind you have to set grid's DataContext to your DataTable:

myDataGrid.DataContext = myViewModel.myDataTable.DefaultView;

In your XAML you need to indicate that the ItemsSource has to rely on binding:

<dg:DataGrid Name="myDataGrid" ItemsSource="{Binding}"/>

Follow this link for more details. Also, you can find a comprehensive example with explanations on CodeProject.

EDIT:

Different approach would be to keep your table as a property. In your window to set the window's data context to the view model and then set the binding to the property in the view model:

The view model:

public DataTable myDataTable { get; set; }

In your window (the one that displays the data grid:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = myViewModel;
}

This way your binding in main window XAML will know where to search for the data - in myViewModel.

In your XAML you don't need a name for your grid using this approach. But the binding has to specify the name of the data source:

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

Upvotes: 1

Related Questions