gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:45:55 25 4
gpt4 key购买 nike

所以标题可能不是很清楚。我有一个 Strings.xaml 文件,其中包含应用程序中使用的几个字符串。

字符串.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.xamlTest_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、Window,直到到达 App 资源。

此外,以后在资源部分下定义的任何资源都会覆盖以前使用相同 key 添加的资源。这适用于在不同资源字典下但不在同一 XAML 文件中定义的资源。如果您尝试用相同的键声明两个项目,它将失败并出现键已存在的异常。


您可以利用上述功能。

假设您要合并 App 资源下的资源,您可以做的是在顶部添加 Strings.xaml,然后添加其他资源字典 Test_1_Strings.xamlTest_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}"/>

它将打印This is a message for test 2

如果您更改顺序并在 Test_2 之后添加 Test_1,textBlock 文本将为 - This is a message for test 1

关于c# - 有默认的字符串资源文件并用自定义的覆盖它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22143142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com