Search code examples
c#wpfwpfdatagrid

WPF: How to Assign data to the DataContext of a Control that is Located in Windows.Resources?


I have a DataGrid inside a Canvas. A List of data is assigned to the DataContext of the DataGrid in code behind. Now I am trying to move the Canvas to Windows.Resources in order to create multiple instances from the control when needed. However, when moving the Canvas to resources, it is not recognized anymore from Code Behind. Any idea how to solve this issue?


Solution

  • You can use FindResource method to get datagrid from window resources.

    Give x:Key to your dataGrid (say x:Key="MyDataGrid") and now in code behind you can get it like this -

    DataGrid dataGrid = (DataGrid)FindResource("MyDataGrid");