1

I figured out how to use data binding in the header of a DataGrid.

<DataGridTextColumn.Header>
   <TextBlock Text="{Binding Path=DataContext.BaseCurrencyName, 
   RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>
</DataGridTextColumn.Header>

My WPF application uses a TabControl. If my initial tab is the tab where the referenced DataGrid appears then there is no problem. If another tab is the initial tab then the next message appears and the heading will be empty.

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=DataContext.BaseCurrencyName; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

The message appears after leaving OnStartup in App.xaml.cs. At that point BaseCurrencyName already has value. And as I said, If my starting tab is the tab with the DataGrid then there is no problem.

Istvan Heckl
  • 864
  • 10
  • 22
  • Is there a reason you need to bind to the DataContext? why not bind to your ViewModel? – Ginger Ninja May 30 '19 at 14:23
  • @GingerNinja with `Binding Path=BaseCurrencyName` there is a different error message: `System.Windows.Data Error: 40 : BindingExpression path error: 'BaseCurrencyName' property not found on 'object' ''DataGrid'` even if the starting tab is the "good one" – Istvan Heckl May 30 '19 at 14:58
  • Well your head View Control (Window, Page, etc) should have the DataContext Bound to it, and you should be able to just do `"{Binding BaseCurrencyName}"` as long as `BaseCurrencyName` is a public property of the Bound ViewModel. So i would immediately guess there may be an issue in the manner in which to set the DataContext of the Parent View. – Ginger Ninja May 30 '19 at 15:04
  • @GingerNinja I checked again `"{Binding BaseCurrencyName}"` works outside the DataGrid (e.g. in a TextBlock) but not in DataGrid Header. – Istvan Heckl May 31 '19 at 05:49
  • 1
    DataGrid columns are not part of the visual tree, so you need some workarounds like https://stackoverflow.com/questions/16965615/how-to-bind-column-header-to-property-in-viewmodel-wpf-mvvm – mami May 31 '19 at 12:59
  • @mami riiiight. i forgot about that. Been a while since i had to set the Header on a datagrid. – Ginger Ninja May 31 '19 at 14:47
  • @mami Thank mami. You helped a lot! – Istvan Heckl May 31 '19 at 15:40

0 Answers0