DataGrid: Binding the Header of TextBoxColumn to Property of DataContext

Feb 25, 2010 at 9:53 PM
Edited Feb 25, 2010 at 9:55 PM

Hello,

is it possible to Bind the Header of a TextBoxColumn to a property of an object, that i set via the DataContext-Property of the DataGrid?

I tried the following, but it didn´t work?

<toolkit:DataGrid>
  <toolkit:DataGrid.Columns>
    <toolkit:DataGridTextColumn Header="{Binding Path=MyTitle}" />
  </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

Here´s the class that i set as DataContext of the DataGrid

public class MyData{
  public string MyTitle { get; set; }
}
and during the initiazation of the DataGrid, i set the DataContext of the DataGrid

myDataGrid.DataContext = new MyData() { MyTitle="Hello World"};

Did i miss something or is there an other way to bind the header?

Thanks for help

 

Mar 17, 2010 at 6:44 PM

There is something really strange about the Header property. You can't even do something simple like bind to the name of the DataGrid...

<toolkit:DataGrid Name="myGrid">
  <toolkit:DataGrid.Columns>
    <toolkit:DataGridTextColumn Header="{Binding ElementName=myGrid, Path=Name}" />
  </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

 

Mar 17, 2010 at 7:18 PM

Just found some helpful information...

http://blogs.msdn.com/vinsibal/archive/2009/04/07/5-random-gotchas-with-the-wpf-datagrid.aspx

which links off to:

http://blogs.msdn.com/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx

 

Which doesn't help in my case. I plan on updating my headers in code behind since they don't change once they're set.

 

Jun 14, 2010 at 11:19 PM

I ran into the same problem using the DataGrid that comes with .NET 4.  I need to change column heading text and visibility dynamically for localization and in response to changing datagrid contents.  I tried the workarounds in those links but despite several hours of screwing around, I couldn't find an acceptable solution.  Looks like I'm going to have to do this in codebehind (so much for MVVM) or find a better datagrid...  I wonder if anyone ever tried localizing this one.

Aug 27, 2010 at 1:36 PM

Any luck with binding in the header?  I saw some work-arounds online with static HeaderStyle and a Dynamic value, but even that did not work for me.  Sad something so simple is nearly impossible to do with this grid.

Aug 27, 2010 at 2:16 PM

If you create the column and create the header with bindings before you add the column to the DataGrid, the bindings will work.  As a workaround i defined all my columns as resources, then added them to the DataGrid in the code-behind.