将资源字符串设置为XAML

11
我知道如何从资源设置字符串, 其中 Text1.Text 是 "Hello"。
但我想要像这样做:
<TextBlock Text = {something here to get GreetingText}/>

其中GreetingText为"Hello"

因此,我也可以从代码中获取相同的字符串

var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var string = loader.GetString("GreetingText");
2个回答

13

包含这个

xmlns:system="clr-namespace:System;assembly=mscorlib"

有一个名为 system:string 的资源,就像这样。

<Window.Resources>
    <system:String x:Key="GreetingText">Hello</system:String>        
</Window.Resources>

并在 XAML 中使用它,如下所示:

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

然后在代码后台中使用它

string s = (string)objectofMainWindow.Resources["GreetingText"];

编辑:回答您的评论

是这样的,资源字典在 Window.Resources 中。

<Window 
    xmlns:system="clr-namespace:System;assembly=mscorlib"

      Your Rest namespaces

     />

<Window.Resources>
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:local="using:ATTFamilyMap.strings">
        <system:String x:Key="GreetingText">Hello</system:String>
    </ResourceDictionary>
</Window.Resources>

Your Code

</Window>

你的意思是我需要创建一个 System.string 文件并将你的 XML 标签放进去吗? - Inder Kumar Rathore
这是我的资源字典,但它给了我一些错误。 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:ATTFamilyMap.strings" xmlns:system="clr-namespace:System;assembly=mscorlib"> <Window.Resources> <system:String x:Key="GreetingText">你好</system:String> </Window.Resources> </ResourceDictionary> - Inder Kumar Rathore
错误1:在元素“ResourceDictionary”上未知的可附加成员“Window.Resources”。 错误2:在XML命名空间“clr-namespace:System;assembly=mscorlib”中未知的类型“String”。 - Inder Kumar Rathore
你的元素顺序有误。请将ResourceDictionary元素放置在Window.Resources元素内部。看一下Nihkil的代码示例! :) - Abbas
1
我无法按照Nikhil在Windows 8中描述的方式使用"<system:String",但由于某种原因,使用"<x:String"却可以正常工作。 - Lee Richardson

12

Nikhil的答案方向正确,但适用于其他平台。

对于Windows 8,您需要在资源目录中执行以下操作:

<x:String x:Key="MyString">This is a resource</x:String>

在你的 XAML 中:

<TextBlock Text="{StaticResource MyString}"/>
在代码中:
string myString = (string)(App.Current.Resources["MyString"]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接