Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to property of datacontext parent- WPF

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?

like image 314
Hodaya Shalom Avatar asked Feb 05 '13 12:02

Hodaya Shalom


1 Answers

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

like image 84
Andrey Gordeev Avatar answered Sep 20 '22 23:09

Andrey Gordeev