Ethan Allen
Ethan Allen

Reputation: 14835

What is the proper way to have a constant string throughout my entire Silverlight C# project?

I want to have a constant string kURL = "http://www.myurl.com/"; throughout my entire project. What's the proper way to do this in a Windows Phone 7 app?

Where would I put this code and what should the proper syntax be?

Upvotes: 4

Views: 2235

Answers (4)

Prakash
Prakash

Reputation: 823

If you want the URL be accessible to both Xaml and C# and if you need this to be accessible to whole project and not whole solution. create a static resource in App.xaml like

<System:String x:Key="kURL">"http://www.myurl.com/"</System:String>

define the namespace "System"

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

Now, you can use this both in xaml and c# code.

In C# code you can use

App.Current.Resources["kURL"];

In Xaml, lets say if you need to use for a textBlock

<TextBlock Text="{StaticResource kURL}" Name="textBlock1" />

Upvotes: 1

shenku
shenku

Reputation: 12458

Create a .Common project for things that you may need to access from all of your projects in your solution (like constants, extension methods, utils etc.), in there simply create Constants class with any Constants that you may need.

Like this:

public static class Constants
{
    #region Nested type: Urls

    public static class Urls
    {
        public static readonly string MyUrl = "http://blablabla.com";
    }

    #endregion

}

Usage would be:

Constants.Urls.MyUrl

Good luck.

Edit Note: Changed to const as per Gabes suggestion

Edit Note2: Changed to static readonly per lukas suggestion

Upvotes: 10

Santhu
Santhu

Reputation: 1525

You define variable in app class and Make use of it. As App class is the main and is available thought the application

Upvotes: 0

evanmcdonnal
evanmcdonnal

Reputation: 48114

Here is a simple tutorial on creating Global Consts in C#. I've used this for .NET, but not Windows Phone. I would assume the same conventions are followed.

http://www.dotnetperls.com/global-variable

Upvotes: 4

Related Questions