I have a DataGrid as shown below
<DataGrid x:Name="dataGrid" Margin="0,5,10,5" AutoGenerateColumns="False" ItemsSource="{Binding Products, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<DataGrid.Columns>
<DataGridTextColumn x:Name="productName" Binding="{Binding Path Name}" Header="Name To Change">
</DataGrid.Columns>
For the code I'm using the DataContextSpy
public class DataContextSpy : Freezable
{
public DataContextSpy()
{
// This binding allows the spy to inherit a DataContext.
BindingOperations.SetBinding(this, DataContextProperty, new Binding());
}
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
// Borrow the DataContext dependency property from FrameworkElement.
public static readonly DependencyProperty DataContextProperty = FrameworkElement
.DataContextProperty.AddOwner(typeof(DataContextSpy));
protected override Freezable CreateInstanceCore()
{
// We are required to override this abstract method.
throw new NotImplementedException();
}
}
Then I have the MVVM Viewmodel with the property which i want to bind the header to like this:
public class ViewModel: ViewModelBase{
string header1;
Public string Header1{
get{return header1;}
set{
Set(ref header1, value);
}
...........
My question is why is it not binding to the property? Anny suggestions?
If Header1
is defined in the same view model class as the Products
property, you could use a HeaderTemplate
like this:
<DataGridTextColumn x:Name="productName" Binding="{Binding Path=Name}">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=DataContext.Header1, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.