I am trying to Bind a TextBlock
inside the Header
of a DataGrid
. However, it doesn't seem to be binding. I've tried setting the DataContext to the one of the root Grid
, but it does not fix the problem.
Here is the exemple:
VIEW
<Window
...
Title={Binding Title}>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" />
<DataGrid Grid.Row="1" x:Name="root">
<DataGrid.Columns>
<DataGridTextColumn>
<DataGridTextColumn.Header>
<TextBlock Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" />
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
VIEW MODEL
public class MainWindowViewModel : BindableBase
{
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainWindowViewModel()
{
Title = "Initial header";
}
}
what I want is to be able to write in the TextBox
and change the header. However, it does seem to be unbinded.
I belive the problem to be with DataContext, but I haven't been able to fix it.
Thanks
The solution was to Bind the dataContext to the ancestor.
<TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=DataGrid, Mode=FindAncestor}, Path=DataContext}" Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" />
I'll leave it here.