Colour Resources in Windows 8 and Windows Phone

It’s easy to create colour resources in Windows platforms within the XAML UI code. These resources can be used to ensure that the colour scheme of your app is consistent, such as using the exact same shade of blue throughout. Another benefit of using resources for colour is that you can instantly change all the colours within your UI by just changing the resource value. This is great for apps that use themes or branding, and also for when you decide you don’t like the colours you initially chose when creating the app.

What is a resource in a Windows app?

A resource or static resource is a setting or object that you can use within your project like a variable. A colour resource stores a set colour, and you can then use this colour to paint UI elements.

First things first

First let’s create some static resources. Open your project (or create a new one) in Visual Studio. Open App.xaml and add the resource as below.

You need to put the resource code within the <ResourceDictionary> area of your App.xaml.

Here is the full XAML for the two colour brush resources we’ll set up. We are making two because there are two ways to define a colour in XAML, so we’ll do one of each.

Code should go in between <ResourceDictionary> and </ResourceDictionary> in the App.xaml file of your project. This ensures that every part of your app can access it. You can be more specific and make resources available only to a specific page, and you can also create a separate resource dictionary file to hold your resources, but those things are outside the topic of this tutorial.

This XAML code applies to both Windows Phone and Windows 8/8.1:

 <SolidColorBrush x:Key="MainColourBrush" Color="#FFF7A619"/>
<SolidColorBrush x:Key="SecondColourBrush" Color="Blue" />

Put the above code into your App.xaml and you can then use those colour resources everywhere in your app.

What does it all mean?

A SolidColorBrush is what XAML uses to paint the colour of most UI elements, such as text and background fills.

You will also notice that we’ve defined our colours in two different ways: with a hex definition (#FFF7A619) and with a word (“Blue”). All colours displayed by computers are defined by the amount of opacity (how transparent the colour is), and the amounts of red, green, and blue in the colour. Hex colour definitions use the hash sign (#) followed by four 2-digit hexadecimal numbers to represent opacity, red, green, and blue. In hex, FF is the largest possible number (255), and therefore any colour that starts with FF is 100% opaque (not transparent at all).


The Blue definition we also used is a predefined colour that Visual Studio recognises. It’s a medium shade of blue. This is actually a predefined colour resource, and there are several of these understood by XAML. You can also create a Color resource to use as well, and the process is very similar to creating a SolidColorBrush.

How to use your resources in your project

Once you’ve set up your colour resource you can use it in your project from the Properties panel for your UI elements/controls. Here you can see how our new colour brush resources look in the Properties panel for a textblock called HeadingText.


And the best part is that you can now change your resource, and instantly every item in your project painted with that resource will change to the new colour!

How to change the resource value at runtime from code behind

My app Scottish Football Hub uses the following technique to change the colour theme of the app to match the user’s favourite Scottish football team:

TryCast(App.Current.Resources("FirstColourBrush"), SolidColorBrush.Color = Colors.Red
TryCast(App.Current.Resources("SecondColourBrush"), SolidColorBrush.Color = Color.FromArgb(255,100,50,75)

And instantly, all UI using the changed colours will be updated to the new colours!

Encapsulate an isolated storage setting in a variable

This is a simple tip that works with both Windows Phone and Windows 8. Dealing with isolated storage settings can be a bit cumbersome. Wouldn’t it be easier if you could treat a stored setting or value like a regular variable?

This tip shows you how to do that using Visual Basic.net in Windows 8 and Windows Phone apps.

What does this tip achieve?

Instead of directly interacting with a setting stored in your app’s isolated storage, this technique lets you treat your settings value like any other variable (or more specifically a property).

Compare the following code for changing the value of the stored (i.e. persistent in isolated storage) NumberOfLives:

NumberOfLives = x + 1

As compared to:

ApplicationData.Current.RoamingSettings.Values("settingname") = "hello world"

Note: you must also make sure the isolated storage setting is created before trying to write to it, or you’ll get an error.

Reading the value:

X = NumberOfLives

Or

X =  ApplicationData.Current.RoamingSettings.Values("settingname")

As you can see, encapsulating the isolated storage value as a property makes the rest of your code easier to write, read, and maintain.

How is the property set up?

The beauty of this technique is that it is very flexible. Properties give you the opportunity to create variables that contain their own internal logic. In this example we’ll just create a very simple property that reads and writes a specified isolated storage value.

Private _numberOfLives as Integer
Public Property NumberOfLives as Integer
    Get
        Return Convert.ToInteger(Isolated.Settings…("NumberOfLivesStored")
    End Get
    Set
        _numberOfLives = value
        ApplicationData.Current.RoamingSettings.Values("NumberOfLivesStored") = _numberOfLives.ToString
    End Set
End Property

A detailed look at the code

Let’s look at the code line by line so you can understand exactly what is happening here.

  1. This line sets up a private variable that is used internally by the property. Code outside of the property doesn’t access this. It’s named the way it is as a conventional way to mirror the property’s own name.
  2. This declares the property as an integer (whole number) variable.
  3. Get marks the start of the code that is executed when the property’s value is being requested (i.e. read).
  4. The return line hands over the value in isolated storage as the result of the Get. This is, in effect, the value of NumberOfLives, but rather than being stored as a variable it has been generated by the Get logic (by reading it from the isolated storage setting).
  5. End Get ends the Get block of code
  6. Set marks the code for setting the value of the property. It is called when the code assigns a value to NumberOfLives, e.g. NumberOfLives = 3.
  7. In this line the variable _numberOfLives is set to “value”. Value is the value that was given to the property to set its value. So in the example above, “value” = 3.
  8. This line takes the value and stores it in the isolated storage key.
  9. End Set ends the set block of code
  10. End Property finishes off the property code.

Is that it?

If you add the code above into your project it will most likely fail! The code is correct, but you’re missing something. To work with isolated storage settings you need to create them before reading or writing their values.

There are two obvious ways to do this. The most foolproof way is to always check if the property exists before reading or writing to it. You could alternatively implement logic in your project that creates all isolated storage properties before they are ever used.

In a future post I’ll put up a full implementation of settings that incorporates logic to check if isolated storage settings exist before attempting to read or write them.

How do I use this?

Once you implemented properties in this way they can be used just like regular variables…except their values will persist when the app is closed! This is ideal for storing application settings that need to accessed by your code a lot.

Download a website as HTML text in Windows 8

A common functionality of apps is to download website content. This downloaded HTML can be parsed for links or content. My app XBMC Buddy uses this technique to find media links in a webpage. In a nutshell The DownloadStringFromUrl function will download the entire HTML from the web address it is given and returns that HTML as a text string. You would use it like this:

 downloadedHtmlText = Await DownloadStringFromUrl("http://www.website.com")

Here’s the code:

 Imports System.Net.Http

Public Class MyFunctions

Public Async Function DownloadStringFromUrl(url As String) As Task(Of String)
 ' return a webpage as a string (the xml, html, etc.)
    Dim client As HttpClient = New HttpClient
    Dim response As HttpResponseMessage
    Try
        response = Await client.GetAsync(url)
    Catch As Exception
        Return Nothing
    End Try

Try
       Dim downloadedHtml as String = Await response.Content.ReadAsStringAsync()
       Return downloadedHtml
   Catch As Exception
       Return Nothing
   End Try

End Function

End Class

What the code is doing

 Imports System.Net.Http

This imports the System.Net.Http namespace, which we need to use HTTP functionality.

 Public Async Function DownloadStringFromUrl(url AsS tring) As Task(Of String)

This is a function (i.e. a method that returns a value), and it is async (can use the await keyword to effectively pause itself while waiting for an action to complete (and let the rest of your application continue its work in the meantime). DownloadStringFromUrl is our function name. (url as String) tells us what variables/information must be passed to the function when it is called – a string that will be referred to as url within the function. As Task(Of String) is our function’s return type – a string task, which is required because this is an async function that doesn’t immediately return a result.

 Dim client As HttpClient = New HttpClient
 Dim response As HttpResponseMessage

These are objects we need to use within the function. HttpClient is the object that does our downloading, and HttpResonseMessage is what we use to interact with HttpClient and give us a response we can test.

 

Try / Catch blocks

Try / Catch blocks are used because downloading from the Internet can be unpredictable. This function will return a value of Nothing if any error occurs, but you can customise the logic to include any error message or fallback you might want to use.

 response = Await client.GetAsync(url)

This line opens the connection to the website. The Await means that this function halts until this line completes. Control goes back to the method that called this function. This asynchronous behaviour is what allows your apps to remain responsive even when they are completing a process, such as downloading, that will take a while to complete. This function will not proceed to the next line of code until the client.GetAsync(url) is complete, as it’s awaiting it. If this succeeds, response will be our connection to the webpage.

 Return Nothing

If client.GetAsync(url) fails the function will return a value of Nothing as it could not connect to the website.

 Dim downloadedHtml as String = Await response.Content.ReadAsStringAsync()

This is the hero line, which downloads the website text and stores it in a string variable called downloadedHtml. We use response from earlier, and use its Content.ReadAsStringAsync() method to get all the text from it.

 Return downloadedHtml

Now we return downloadedHtml as the result of the function. An example usage Here is a line of code from an app that is downloading HTML from a webpage. Note that we use the Await keyword because our function uses Await.

 Public Sub DownloadHtmlFromWebPage()
Dim rawHtmlText as String
rawHtmlText = Await DownloadStringFromUrl("http://www.website.com")
MyTextBox.Text = rawHtmlText
 End Sub

When the above method is run, the download will start. This method effectively pauses once the download starts, and lets the rest of the program continue while downloading continues in the background. Once the download is complete, the value of the awaited download gets put in the rawHtmlText string.