polfosol polfosol - 3 months ago 43
C# Question

WPF - Binding the DataContext of a DataGrid to DataTable

I have a

DataGrid
in my WPF window. I bind its
DataContext
to a
System.Data.DataTable
. When I construct and fill my
DataTable
, the
DataGrid
updates and works perfectly. Now I want to find some elements in my
DataTable
and highlight their associated cells in the
DataGrid
. How can I do this using the MVVM pattern? What other property of the
DataGrid
I should bind in order to achieve this?

I have been googling for two hours and so far I got nothing. Any hints would be appreciated.

Answer

The main problem was with the binding. One shall not bind the DataContext of a DataGrid to a DataTable. The better way is to bind its ItemsSource to the DataTable. Although the result would appear the same.

Secondly, abiding to the MVVM pattern is sometimes really painful and seems unnecessarily complicated. It seems there is no harm in doing some works programmatically.

And finally, this great answer helped me a lot. I refer the future readers with the same issues to that.