Me Myself & C#

Manoj Garg’s Tech Bytes – What I learned Today

Posts Tagged ‘XAML’

Accessing Strings from Resource File in XAML markup

Posted by Manoj Garg on March 18, 2009

Its a good practice to have constant strings in Resource files i.e. files with .Resx extensions.

Accessing the resource files in Code behind is straight forward. syntax is pretty simple

<<Resource File Name>>.<<String Key in the resource file>>

For example if your resource file name is “Strings.Resx” and the string key is “My_Const_String”. To access this value in code behind you can write “Strings.My_Const_String” and this will give you the key value defined in the resource file. But what if, you want to access this resource string in XAML file only.

This may be very basic stuff but as I am ramping myself in WPF, I had tough time finding a way to do it. After 30 odd minutes of googling found a way here. So thought of writing it on my blog.

Accessing the resource string is a thee step process.

  1. Make the resource strings Public: By default the resource strings are internal. so if we want to use then in XAML we need to change their modifier to public. To do this just open the resource file and change the value of “Access Modifier” drop down to public from internal. Following image show a snapshot of this in VS 2008

resource 

    2.   Register the namespace with the xmlns

E.g. Suppose you are default resource file, created with WPF project, Resources.Resx in the Properties folder of your project. Then use the following syntax to register your namespace.

   1: xmlns:const="clr-namespace:FileExplorer.Properties"

 

   3.   Use x:Static to access to static resource strings since all the strings stored in a resource file are static properties of that resource class.

E.g Now you have a String named “Window_Title_String” and if you want to set the title of the current window to this string. you can use the following code snippet

   1: <Window x:Class="SampleProj.View"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:const="clr-namespace:SampleProj.Properties"
   5:     Title="{x:Static const:Resources.Window_Title_String}"
   6: >

 

Hope it helps.

Ha-P Binding 🙂

Posted in .Net 3.5, WPF, XAML | Tagged: , , | 9 Comments »