C# 将资源字符串设置为 XAML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12890279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:50:50  来源:igfitidea点击:

Set resource string to XAML

c#xamlwindows-8microsoft-metro

提问by Inder Kumar Rathore

I know how to set string from resource
<TextBlock x:Uid="Text1"/>where Text1.Textis "Hello"

我知道如何设置字符串从资源
<TextBlock x:Uid="Text1"/>那里Text1.Text是“你好”

But I want to do like this

但我想这样做

<TextBlock Text = {something here to get GreetingText}/>

where GreetingTextis "Hello"

GreetingText“你好”在哪里

So that I may get the same string from code also as

这样我也可以从代码中获得相同的字符串

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

采纳答案by Shahar Prish

Nikhil's answer is on the right track, but is right for other platforms.

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

For windows 8, you need to do the following in your resource directory:

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

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

In your xaml:

在您的 xaml 中:

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

In code:

在代码中:

string myString = (string)(App.Current.Resources["MyString"]);

回答by Nikhil Agrawal

Include this

包括这个

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

Have a resource of system:stringlike this.

有这样的资源system:string

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

and use it in xaml as

并在 xaml 中使用它作为

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

and use it in code behind as

并在后面的代码中使用它作为

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

Edit: Answer to your comment

编辑:回答您的评论

Its this way. Resource Dictionary is inside Window.Resources

就这样。资源字典在里面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>