微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 拥有默认字符串资源文件并使用自定义文件覆盖它

因此标题可能不完全清楚.
我有一个Strings.xaml文件,其中包含应用程序中使用的几个字符串.

Strings.xaml
    

<!-- GENERAL FOR ALL TESTS -->
    <my:String x:Key="AppTitle">AppName</my:String>        
    <my:String x:Key="TestName1">test_1</my:String>
    <my:String x:Key="TestName2">test_2</my:String>

    <!-- DEFAULT MESSAGES -->
    <my:String x:Key="TestMessage">This is a default message</my:String>
    <my:String x:Key="TestDescription">This is a default description</my:String>

    <my:String x:Key="OnlyCustomInTest2">This string is used as a default message if not overridden by custom resource file</my:String>

</ResourceDictionary>

此资源文件非常有用.我想知道的是,如果有任何内置方式我可以使用Strings.xaml作为认资源文件,然后覆盖为不同程序模式自定义的特定字符串?就像使用Strings.xaml认并使用Test_1_Strings.xaml和Test_2_Strings.xaml来覆盖自定义消息的某些字符串一样.

Test_1_Strings.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:my="clr-namespace:System;assembly=mscorlib">

    <!-- CUSTOM FOR TEST 1 -->
    <my:String x:Key="TestMessage">This is a message for test 1</my:String>
    <my:String x:Key="TestDescription">This is a description for test 2</my:String>

</ResourceDictionary>

Test_2_Strings.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:my="clr-namespace:System;assembly=mscorlib">

    <!-- CUSTOM FOR TEST 2 -->
    <my:String x:Key="TestMessage">This is a message for test 2</my:String>
    <my:String x:Key="TestDescription">This is a description for test 2</my:String>
    <my:String x:Key="OnlyCustomInTest2">This is the overridden message for test 2</my:String>

</ResourceDictionary>

我想这样做的原因是因为我有许多不同的程序模式,其中大多数资源是相同的,但有些是自定义的.我不必在8个不同的资源文件中更改共享条目,而只能在一个地方完成.

解决方法

WPF中的资源查找从下到上遍历,即任何资源使用将首先在其父容器中查找资源,该容器可以是Grid,StackPanel等.如果在父容器中找不到将在父容器中查找资源,依此类推到UserControl,窗口直到它到达App资源.

此外,稍后在资源部分下定义的任何资源都会覆盖先前使用相同密钥添加的资源.对于在不同资源字典下定义但不在同一XAML文件中的资源,情况也是如此.如果您尝试使用相同的密钥声明两个项目,则它将失败并且密钥已存在异常.

您可以利用上述功能进行使用.

假设您正在合并App资源下的资源,您可以做的是在顶部添加Strings.xaml,然后添加其他资源字典Test_1_Strings.xaml和Test_2_Strings.xaml.这样,将覆盖具有相同名称的资源,并始终解析最后定义的资源.

<Application.Resources>
   <ResourceDictionary>
     <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Strings.xaml"/>
        <ResourceDictionary Source="Test_1_Strings.xaml"/>
        <ResourceDictionary Source="Test_2_Strings.xaml"/>
     </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Application.Resources>

因此,当您声明TextBlock以引用StaticResource TestMessage时.

<TextBlock Text="{StaticResource TestMessage}"/>

它会打印这是测试2的消息.

如果更改顺序并在Test_2之后添加Test_1,则textBlock文本将为 – 这是测试1的消息.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐