Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom column template for DataGrid
    primarykey
    data
    text
    <p>I have a DataGrid bound to a DataTable.DefaultView, which renders the grid using auto generation of columns. That part works fine. However, for some columns I would like to use a custom template. The problem is that columns in the table change on each load, so the solution needs to be generic.</p> <p>I can hook into the AutoGeneratingColumn event as described <a href="http://msdn.microsoft.com/en-us/library/cc903950%28v=vs.95%29.aspx" rel="nofollow">here</a>, but still have problem with defining the template binding:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;DataTemplate x:Key="customCellTemplate"&gt; &lt;TextBlock Text="{Binding ???"&gt;&lt;/TextBlock&gt; &lt;/DataTemplate&gt; &lt;/UserControl.Resources&gt; (...) &lt;DataGrid ItemsSource="{Binding DefaultView}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"&gt; &lt;/DataGrid&gt; </code></pre> <p>And my code behind:</p> <pre><code>private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { string colName = e.PropertyName; if (someCondition) { var templateColumn = new DataGridTemplateColumn(); templateColumn.Header = colName; templateColumn.CellTemplate = (DataTemplate)Resources["customCellTemplate"]; templateColumn.SortMemberPath = colName; e.Column = templateColumn; } </code></pre> <p>As you can see I don't know how to define the binding in the column template, because the column name changes. </p> <p><strong>EDIT:</strong></p> <p>In addition to the accepted answer - sometimes it's easier to create the entire template programmatically as described here: <a href="http://fczaja.blogspot.com/2013/12/wpf-datagrid-custom-template-for.html" rel="nofollow">http://fczaja.blogspot.com/2013/12/wpf-datagrid-custom-template-for.html</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload