Accessing Messages |
To access strings, you can use the MessagesBundle class. Typically you would create a DirectoryMessagesBundle instance where lang.xml will be read from disk, although StringMessagesBundle can be used if you have lang.xml contents in a string.
The only public method in MessagesBundle is:
public string GetString(string type, string phrase, object obj)
Where,
type is the name of the section in the XML file that should be used to generate the string, for example Strings or Announcements.
phrase is the name of the phrase.
obj is an optional object that will provide values to use in the string. If it is not required then it should be set to null.
As an example,
messagesBundle.GetString("Strings", "gb_searching_for_gps", null);
will return the 'Searching for GPS' string.
If an object is supplied, and GeoBase finds a node with a From attribute, it uses reflection to find a field, property or method (in that order) with the same name as the From attribute. If the From attribute contains a "." then GeoBase will walk through the various fields, properties and methods to get the required value.
Consider the following classes:
public class TurnOperation { public TurnDirection Direction; } public class FarAwayTurn { public TurnOperation Operation; public string Distance; } public enum TurnDirection { Left, Right }
and XML snippet:
<Lang> <MyStrings> <Phrases> <Phrase Id="far_away_turn"> In <GetString From="Distance"/> turn <LookupGroup From="Operation.Direction"/> </Phrase> </Phrases> <Groups> <TurnDirection> <Left> left </Left> <Right> right </Right> </TurnDirection> </Groups> </MyStrings> </Lang>
This code could be used to describe a FarAwayTurn:
FarAwayTurn myFarAwayTurn = new FarAwayTurn(); string myPhrase; myPhrase = myMessagesBundle.GetString("MyStrings", "far_away_turn", myFarAwayTurn);
In the GetString() method above, the string returned is based on the far_away_turn phrase from the configuration file's MyStrings section. In the Phrase tag (<Phrase Id="far_away_turn">) there are two instructions:
Both of these instructions, through reflection, access the relevant data from the given object (myFarAwayTurn). The first instruction (<GetString From="Distance"/>) uses the object's data directly, and simply returns the string of myFarAwayTurn.Distance. The second instruction is slightly more involved. This time the object provides the instruction with the information on how to locate the required string from the <Groups> section in the XML document. In this instance, it will look up either <Left> or <Right> in the <TurnDirection> section.