查找Josh Smith關於DataContext Spy的博客,其中DataContextSpy類使用Hillberg的Freezable技巧從不在邏輯樹中的對象獲取對繼承上下文的訪問權限。 DataContextSpy非常簡單,所以在許多場景中它應該是可重用的。
這裏是你如何使用它的頭文件(我用這一切的時候,不僅DataGrid.Headers):
<DataGrid...
<DataGrid.Resources>
<myNamespaces:DataContextSpy x:Key="dcSpy" DataContext="{LocalizedText}"/>
.......
<DataGridTemplateColumn Header="{Binding Source={StaticResource dcSpy}, Path=DataContext.Task_Toolbar_AddButton}">
編輯: 我似乎無法找到它的任何位置他的博客,也許他把它歸檔了,所以在這裏,我會爲你添加它。貼吧,引用它在XAML正如我上面顯示,然後用它的DataContext拔出你想要的數據綁定:
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();
}
}
頭不是在邏輯樹... – 2012-04-19 22:26:29