Vijay Chavda
Vijay Chavda

Reputation: 862

Bind DataGridColumnHeader with selected row's property

Consider the following ViewModel:

public class MyViewModel 
{
    public ObservableCollection<Foo> foos { get; set; }
}

[PropertyChanged.ImplementPropertyChanged]
public class Foo
{
    public string Name { get; set; }
    public string NameHeader { get; set; }
}

Note that I am using Fody's PropertyChanged to make my ViewModel properties implement INotifyPropertyChanged.

And I have the following DataGrid:

<DataGrid x:Name="FooTable"
          ItemsSource="{Binding Path=foos}"
          AutoGenerateColumns="False"
          CanUserAddRows="True"
          AutomationProperties.IsColumnHeader="True"
          SelectionMode="Single"
          SelectionUnit="FullRow">

          <DataGrid.Columns>
              <DataGridTextColumn 
                  Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                  Header="{Binding NameHeader, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
                  Width="Auto" />
          </DataGrid.Columns>
</DataGrid>

The Binding of Header with NameHeader won't work! Ofcourse then I realized that different Rows will have different values of NameHeader.

So what I really want is to bind column's Header with selected row's NameHeader. How can I achieve that?

Upvotes: 3

Views: 228

Answers (1)

mm8
mm8

Reputation: 169190

Use a HeaderTemplate with a TextBlock that binds to the SelectedItem property of the DataGrid:

<DataGridTextColumn Binding="{Binding Name}" Width="Auto">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=SelectedItem.NameHeader, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

Upvotes: 1

Related Questions