[英]WPF Dynamic DataGrid headers
Since it is not possible to have DataGrid
headers dynamically read some resource file, I used a method found here on SO to do so. 由于不可能使DataGrid
标头动态读取某些资源文件,因此我在SO上找到了这里使用的方法。 It is working by having a TextBlock
as a resource, which is dynamically reading some other string
resource. 它通过将TextBlock
作为资源来工作,该资源正在动态读取其他string
资源。 Something like this: 像这样:
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="{StaticResource dghName}"/>
<DataGridTextColumn Header="{StaticResource dghAge}"/>
</DataGrid.Columns>
</DataGrid>
and in the resources I would have this: 在资源中,我将拥有:
<TextBlock x:Key="dghName" Text="{DynamicResource Name}"/>
<TextBlock x:Key="dghAge" Text="{DynamicResource Age}"/>
<sys:String x:Key="Name">Name</sys:String>
<sys:String x:Key="Age">Age</sys:String>
The string resources are within some separate file and when I just swap it for some other file with the same keys but with texts on some other language, the headers are changed. 字符串资源位于某个单独的文件中,当我仅将其交换为具有相同键但带有其他某种语言的文本的其他文件时,标题就会更改。
This was all working just fine, until there came a need for using the same resource on two places. 一切都很好,直到需要在两个地方使用相同的资源。 I have the same DataGrid
within two TabItem
s. 我在两个TabItem
具有相同的DataGrid
。 When I open the first one, the headers are shown normally, then I switch to the other tab, the headers are there as well. 当我打开第一个时,标题将正常显示,然后切换到另一个选项卡,标题也将显示在其中。 Now, when I change back to the first TabItem
, the headers are empty. 现在,当我改回到第一个TabItem
,标题为空。 Same thing happens if I open the second tab first - when I switch to the first tab and then back to the second one, the headers are empty. 如果我先打开第二个选项卡,也会发生同样的事情-当我切换到第一个选项卡然后又回到第二个选项卡时,标题为空。
It would have more sense to me, if there were no headers when I open the second tab, but they are show on both tabs for the first time, and then they are gone, when I open a tab (which was the first one to open) for a second time. 如果我在打开第二个选项卡时没有标题,但它们第一次显示在两个选项卡上,然后在我打开一个选项卡时它们消失了,那对我来说更有意义(这是第一个打开)。
The resources are within resource dictionaries, as XAML
files. 资源在资源字典中,作为XAML
文件。
You can add x:Shared="false" attribute to the elements. 您可以将x:Shared =“ false”属性添加到元素。
This way each data grid receives it's own instance of resource instead of trying to share the same one: 这样,每个数据网格都将接收其自己的资源实例,而不是尝试共享相同的资源实例:
<TextBlock x:Key="dghName" Text="{DynamicResource Name}" x:Shared="false" />
<TextBlock x:Key="dghAge" Text="{DynamicResource Age}" x:Shared="false" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.