如何使用静态资源(.resx)作为资源字典中具有数据类型的数据模板的键?

时间:2019-01-09 17:29:20

标签: c# wpf xaml localization resx

我在我的棱镜组件中定义了一个资源字典,其中包含数据模板。我的目标是在其上定义DataType=""属性以确保类型安全,同时将我的x:Key=""字符串存储在单独的 .resx 文件中以供重复使用。我发现this stackOverflow answer讨论了使用{x:Static }来访问文本的用法,并且需要一种更为冗长的方法来避免以这种方式对其进行访问。

不幸的是,似乎同时使用上述方法会导致x:Key默认为nameof(DataType),这在使用不同的键定义多种类型时会引起问题。

这是该场景的一个示例:

<ResourceDictionary 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     x:Class="Namespace.Class"
                     xmlns:resources="clr-namespace:Namespace"> 

    // Key is the value of the .resx string "MyResxString"
    <DataTemplate x:Key="{x:Static resources:Text.MyResxString}"/>

    // Key is "myClass"
    <DataTemplate DataType="{x:Type myClass}"/>

    // Key is "example"
    <DataTemplate x:Key="Example" DataType="{x:Type myClass}" />

    // Key is unexpectedly "myClass" and my static string is ignored in the key attribute
    <DataTemplate x:Key="{x:Static resources:Text.MyResxString}" 
       DataType="{x:Type myClass}"/>

</ResourceDictionary>

这是此绑定的预期结果吗?还是不对劲?是否有其他方法可以做同样的事情? (我知道.resx首先并不是最好的方法,但这是我们的标准)

0 个答案:

没有答案