将 DataGrid 列标题绑定到 DataContext [英] Binding DataGrid column Header to DataContext
问题描述
我知道以前有人问过这个问题,但以前"的答案似乎都不适合我......
I know this question has been asked before, but none of the "previous" answers seems to work for me...
我在我的应用程序中实现了多语言功能,因此我必须将我的 DataGrid 列的标题绑定到 DataContext.
I have implemented a functionality for multi languages in my application, and I therefor have to bind the header of my DataGrid columns to the DataContext.
我在 DataContext 中使用字典(在下面的示例中称为 Text)来存储文本,并且该绑定适用于文本块、按钮等.
I use a dictionary (called Text in the example below) in the DataContext to store the texts, and the binding works fine with textblocks, buttons etc.
<TextBlock Text="{Binding Text[Name], FallbackValue='Name'" />
但是,我无法在 DataGrid 列的 Header 属性上使用它.
But, I can't get this to work on the Header-attribute of the DataGrid columns.
我在某处读到,我需要为列/标题编写一个模板来实现这一点,但我也想不通.
I read somewhere, that I need to write a template for the column/header to achieve this, but I can't figure this out either.
推荐答案
您可能需要返回树来获取所需的 DataContext:
You may need to walk back up the tree to get the DataContext you want:
<DataGridTextColumn Binding="{Binding Name}">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.Text[Name],
RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
直接在 Header
属性上执行此操作将不起作用,因为它无法就地解析,因为列是未出现在树中的抽象对象.
Doing this directly on the Header
property will not work because it cannot be resolved in-place as the column is an abstract object not appearing in the tree.
这篇关于将 DataGrid 列标题绑定到 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!