7

I have a DataGrid:

 <DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
     <DataGrid.Columns>
          <DataGridTextColumn Header="?" Binding="{Binding l}">
          </DataGridTextColumn>
     </DataGrid.Columns>
  </DataGrid>

In DataContext of the DataGrid there is the collection of class X:

public ObservableCollection<xxx> col{ get; set; }// = DataContext of DG

    private string lName;

    public string LName
    {
        get { return lName; }
        set
        {
            lName= value;
            NotifyPropertyChanged("LName");
        }
    }

I want lName will be the header of a particular column in DataGrid

I try this way:

 <DataGridTextColumn  Binding="{Binding l}">//l=prop of xxx class that contains the collection
                                <DataGridTextColumn.HeaderTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding DataContext.LName,
                       RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                                    </DataTemplate>
                                </DataGridTextColumn.HeaderTemplate>
                            </DataGridTextColumn>

It did not work

how can do this?

Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111

2 Answers2

17

Try {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.LName}

Also I wouldn't play with name cases. WPF is pretty case-sensivity. Avoid of using one-symbol names

Andrey Gordeev
  • 30,606
  • 13
  • 135
  • 162
  • This does not appear to work because the DataGridColumn is not apart of the visual tree. So it can't do the lookup. Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window' This is on the VisibilityProperty in the column. This question seems to answer it with x:Reference http://stackoverflow.com/questions/22073740/binding-visibility-for-datagridcolumn-in-wpf – user99999991 Jul 16 '16 at 02:05
1

Binding paths are also case-sensitive. There is no property lName in your DC.

Marius
  • 1,042
  • 1
  • 8
  • 19