Monday, March 8, 2010

Global variable in Silverlight

To share the value across, global variables are required. Similarly, if a value has to be passed from one XAML to another global variable concept can be used.

Steps:
1) Create property in APP.XAML

Private _gloVar As String

Property gloVar() As String
Get
Return _gloVar
End Get
Set(ByVal value As String)
_gloVar = value
End Set
End Property


2) From one XAML's code behind, create object for APP and then get the current instance.
3) Using that object, property created in step 1 is accessible. Using this set the value.

'Setting value from one xaml
'get the current application object
Dim objApp As App = App.Current

'set the value to the app var
objApp.gloVar = "Value you want to store"

4) From where (XAML) you want value to be used, get current instance of the APP like described in step 2 and access the property value from that object.

'Reading the value from another xaml
'get the current Application object
Dim objApp As App = App.Current

'read the application variable
TextBlock.Text = "Content loaded from global variable: " + objApp.gloVar

2 comments:

Daniel said...

Nice tip thanks.
I would add to it slightly by rapping all your global variables in a class and then maintaining an instance of the class (called Globals for example) in your App.xaml.cs class. Then you can refer to you variables as App.Current.Globals.VariableName
Which is the same thing just a bit easier to read :)

Amol Kagde said...

Hi,

This is realy trick working and it helps me lot!!

Thanks a tone!

Amol