首页 > 解决方案 > 如何使用静态资源 (.resx) 作为资源字典中具有 DataType 的 DataTemplate 的键?

问题描述

我在包含数据模板的 prism 程序集中定义了一个资源字典。我的目标是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 并不是最好的方法,但它是我们的标准)

标签: c#wpfxamllocalizationresx

解决方案


推荐阅读