Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Vijay Chavda Avatar asked Dec 11 '25 21:12

Vijay Chavda


1 Answers

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>
like image 162
mm8 Avatar answered Dec 14 '25 11:12

mm8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!