Reputation: 761
I have a code in which Binding doesn't work
<DataGridTextColumn Header="{Binding LocalizedText.Task_Toolbar_AddButton}" />
For button:
<Button x:Name="addTaskButton" Click="addTaskButton_Click">
<TextBlock Text="{Binding LocalizedText.Task_Toolbar_AddButton, Mode=OneWay}" />
</Button>
it works fine, but for datagrid header doesn't work at all.
Upvotes: 1
Views: 2494
Reputation: 6316
Look up Josh Smith's blogs about DataContext Spy, where DataContextSpy class uses Hillberg’s Freezable trick to gain access to an inheritance context from an object that is not in a logical tree. DataContextSpy is very simple, so it should be reusable in many scenarios.
Here's how you can use it on headers (I use it all the time, not only on DataGrid.Headers):
<DataGrid...
<DataGrid.Resources>
<myNamespaces:DataContextSpy x:Key="dcSpy" DataContext="{LocalizedText}"/>
.......
<DataGridTemplateColumn Header="{Binding Source={StaticResource dcSpy}, Path=DataContext.Task_Toolbar_AddButton}">
EDIT: I can't seem to find it anywhere on his blog, maybe he archived it, so here, I'll just add it for you. Paste it, reference it in XAML as I showed above, then use it's DataContext to pull out what the data you want to bind:
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 ();
}
}
Upvotes: 2