2012-10-15 54 views
9

我知道如何從資源
<TextBlock x:Uid="Text1"/> 其中Text1.Text是「你好」設置資源字符串XAML

設置字符串,但我想要做這樣的

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

其中GreetingText是「你好」

這樣我就可以從代碼中得到相同的字符串

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

回答

10

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"]); 
+0

簡單而簡單:) –

11

包含此

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> 
+0

你的意思是說我必須創建一個System.string文件並將其中的xml標籤? –

+0

System.string資源。 –

+0

這是我的資源字典,它給了我一些錯誤。 ' Hello