Wp7nl utilities Contribution
When building apps for Windows Phone I use my own library. I’m a “lazy” developer and don’t like writing code twice. So I place a lot of code that can be reused, like behaviors, converters and extension methods, in my library. For I while I’ve been thinking about sharing the library as an open source project on Codeplex, but in the end decided to contribute to the Wp7nl Utilities project of Joost van Schaik. The first bunch of utilities are added. I will continue to add more and describe those on my blog too.
Actions for Launchers
I often have simple trigger actions that need to be executed in my apps. For example, opening a URL in Internet Explorer or sending an email. Because I use Blend a lot (and I’m lazy ;) ), I just like to drag and drop an action to a button or text block and be done with it. The great thing about actions and behaviors is that you can bind the the properties which makes them very useful in templates.
At this point only a few of the possible Windows Phone Launchers are available as trigger actions, but I’m sure the list will grow over time. If you would like one added just let me know and I’ll see what I can do.
Using these actions is very simple. The code surrounding the action is pretty much the same for all actions, only the event name might change. The NavigateToUrlAction performs a WebBrowserTask. It opens up the Url property so you can bind to it. As a small extra feature it checks if a network connection is available and shows a message if there isn’t. This message can be customized as well.
<Button Content="Wp7nl" HorizontalAlignment="Left" VerticalAlignment="Top">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<behaviors:NavigateToUrlAction Url="http://wp7nl.codeplex.com"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
This action executes the EmailComposeTask. The “To”, “Subject” and “Body” properties can be bound to.
NavigatieToMarketplaceDetailAction
This action executes the MarketPlaceDetailTask. It opens up the marketplace and shows the details of your app.
Getting people to review your apps is crucial for a successful app. This action executes the MarketplaceReviewTask and makes it very easy for users to review.
Sharing links is a very common task in apps. This action executes the ShareLinkTask. So you can use the native sharing features of the phone. The “LinkUri”, “Message” and “Title” properties can be bound to.
I ran into cases where I wanted to limit the number of characters a user can enter. This behavior an only be used with a TextBox element. You can set the maximum number characters that can be entered in the “MaxChars” property. As a bonus feature you can have the phone vibrate a little when the maximum number of characters is reached.
<TextBox x:Name="LimitedTextbox">
<i:Interaction.Behaviors>
<behaviors:LimitTextBoxBehavior MaxChars="25" Vibrate="True"/>
</i:Interaction.Behaviors>
</TextBox>
Visible On Locale Behavior
The VisibleOnLocaleBehavior sets the attached element to visible if the current UI language of the phone matches the specified two letter ISO language name and hides it when it doesn’t. The behavior can be used I you have certain element, like images, that are language specific.
<TextBlock Text="English" >
<i:Interaction.Behaviors>
<behaviors:VisibleOnLocaleBehavior LanguageCode="en"/>
</i:Interaction.Behaviors>
</TextBlock>
<TextBlock Text="Nederlands">
<i:Interaction.Behaviors>
<behaviors:VisibleOnLocaleBehavior LanguageCode="nl"/>
</i:Interaction.Behaviors>
</TextBlock>
Visibility In Trial Behavior
The VisibilityInTrialBehavior sets the attached element to visible or collapsed if the app is in trial mode. Whether the attached element should be visible or collapsed is determined by the “Visibility” property.
<TextBlock Text="Not in trial mode">
<i:Interaction.Behaviors>
<behaviors:VisibilityInTrialBehavior Visibility="Collapsed"/>
</i:Interaction.Behaviors>
</TextBlock>
This behavior makes use of the TrialHelper. This helper is used to see if your app is running in trial mode. The be able to run your application in trial mode you can add “TRIAL” as a conditional compilation symbol to fake it when debugging.
Converters
I’ve added a couple of converters to the Wp7nl library. Most of which are very simple.
Let’s start with the one that needs the most explanation. The ObjectToStringConverter is used to create a nicer representation of an object. Add properties of the bound object between { } to the converter parameters.
Take, for example a Person class.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Whenever you would like to have a textblock show the last name and the first name separated with a comma, you could just add that to the converter parameter.
For this example I’ve set the datacontext of the mainpage to a new instance of the person class directly in the constructor. You wouldn’t do that in a real application of course, but you’ll get the idea.
public MainPage()
{
InitializeComponent();
DataContext = new Person{FirstName = "Larry", LastName = "Laffer"};
}
Than I’ve added a databinding to the textblock.
<TextBlock Text="{Binding ConverterParameter=\{LastName\}\, \{FirstName\}, Converter={StaticResource ObjectToStringValueConverter}}"/>
When creating the binding in Blend, you don’t have to escape the curly brackets, as shown in the image below.
Returns Visibility.Collapsed for any value that is null, empty, only whitespaces or an empty guid. Very useful to hide empty stuff. You don’t want to show a navigate to URL button if the URL is empty, for example.
Removes all HTML from a string and decodes ‘&XXXX’ to regular chars. Often when data is requested from external services like Twitter or Facebook, it contains HTML at some point. This HTML has to be converter to either a regular string or to some sort of rich text block. This converter does the first, removing all HTML. <BR /> tags are changed to new lines.
Converts a string to all lowercase characters. Useful for headers.
Converts a string to all uppercase characters. Useful for titles.
Customized Sample data
Intro
When working on Windows Phone or Silverlight applications I use the sample data feature of Blend a lot. I like to see what I’m working on. The only downside of this sample data is that it rarely mirrors the data (unless I’m working on the chair application for a company called Lorem Ipsum). I’d like to see Dutch phone numbers, cities and postal codes. So I’ve decided to create my own list of sample data. At first I thought I had to build a new extension for Blend to be able to customize the data. It turned out to be far less complicated.
How?
The “String” type of sample data is stored in two files. If you’ve installed Blend on the default location you can find these files at:
- Blend for Visual Studio ==> C:\Program Files (x86)\Microsoft Visual Studio 11.0\Blend\SampleDataResources\en\Data
- Expression Blend 4 ==> C:\Program Files (x86)\Microsoft Expression\Blend 4\SampleDataResources\en\Data
The first file, LoremIpsum.txt, contains a dummy text. This text is loosely based on Latin an is commonly used as dummy text. The second file, SampleStrings.csv, is a comma delimited file that contains the names and words you are probably used to when working with sample data. All you need to do if you want to create custom data is replacing these files.
Because I’m Dutch and would like to use Dutch dummy text I replaced the contents of the LoremIpsum.txt file with some of the generated text on this page. This immediately makes the random generated text look Dutch.
Replacing the SampleStrings.csv file was a bit more complicated. I assumed the strings had to be in the exact same format as they were, but I was wrong here. You can do whatever you want with this file, as long as the first row of elements are the names of the data you are fine. These names show up in the Format combobox.
Besides the obvious things like first name, last name and addresses, I added a few thing I always needed as sample data but didn’t have. I added image urls and a thumbnails that point to http://lorempixel.com. That way I have “real” images when binding the sample data to the source property of an image. I also added dummy tweets. These are just texts but sometimes start with @ or RE, can contain a url or sometimes have a random hash tag.
Download
You can find both files in SampleData. I also include .bak files of the original files.

Styling Windows Phone 7 Pivot Control Titles
For a Windows Phone 7 application I’m currently working on I needed to change the font the titles of a couple of PivotItems on a Pivot control. Normally I won’t recommend using another font than Segoe WP for this, but sometimes the branding of the app leaves you no other choice.
Changing the font of the title turned out to be a lot harder than I thought. To spare you the trouble, here’s how it’s done in Expression Blend.
Walkthrough
For this walkthrough I created a very cool app, containing a Pivot control with three PivotItems.

Changing the font of the title of the Pivot itself is easy. With the Pivot selected in the Objects and Timeline pane set the font property to whatever you need.


Setting the same font for the titles of the PivotItems is a bit more complex. With the Pivot control still selected, click on the Pivot(just below the tabbar above the design area) and follow Edit Template –> Edit a Copy…

The Create Style Resource dialog appears. You could name the style here and place it a Resource Dictionary if you like. For now, just hit OK.

You’ll end up with the inner components of the Pivot.

Select the HeaderListElement from the Objects and Timeline pane. This is the bar that contains the titles of the PivotItems. And go to HeaderListElement –> Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy…

I probably should give my style a cool hip name, but for the demo I’ll just leave that up to you and hit OK right away…

We have reached our final destination, the template that holds the properties for the title of the PivotItem.
To set the font of the titles you need to do a little trick. Because the ContentPresenter doesn’t have a font property you need to change it to something else, preferably another control that can contain content. So, change the xaml of template and turn the ContentPresenter into a ContentControl.

The ContentControl has the needed text properties. I’ve set the font to the one I needed and changed the font size to 70pt. A small side note: make sure you embed the font in your app, otherwise it won’t work when the app is running in the emulator or on the phone.

As you might have notices, the color of the titles is grey and white. Which isn’t very cool. So the last part of this tutorial will show how to change that.
Have a look at the visual states on the State pane and notice there are two states. Selected and Unselected.
Select the Selected state and notice the red border around the design area indicating every property you change will be recorded into this visual state. You can use resources in your visual states. Which is handy when you want to use the phone’s accent color. Make sure the element named "ContentPresenter” is selected in the Objects and Timeline pane and select the foreground color brush. Select the Color resources tab and set the color to the PhoneAccentColor.
To show a bit of what the visual states can do, and have a little bit of fun with the Pivot control too, we’re going to make the selected state slightly bigger than the unselected state. With the Selected state and the “ContentPresenter” element still selected change the scale of the RenderTransform to 1,1 for both the X and Y scale.

To make the scaling a bit more noticeable when the app is running. I’m going to set the transition between states to 0.5 seconds, with a CubicInOut easing.

And that’s is. You’ve changed the title of the items in a Pivot control.
Prevent ugly images on Windows Phone
Problem
Sometimes images look nice on a regular computer screen, but when used in your Windows Phone application they become ugly. This effect is most often seen on gradients and images with smooth coloring. In gradient images you’ll start to see stripes and bands. It looks like the colors in the image don’t blend anymore.
Below are the 32bit and 16bit versions of the same images. Notice the banding on the right one.
Cause
This problem may be caused by a setting in your application or just by screen of the phone itself. It occurs when a 32bit image is shown on a 16bit screen. Because there are way more shades of colors available in 32bit images than in 16bit images, you’ll start to see these artifacts when the depth doesn’t match the screen.
Solution
The solution is relatively simple. Just scramble the pixels a bit to make the colors look like they blend. This process is called dithering. Maybe you’ll remember, back in the days with Windows 3.11, you often saw ‘gradients’ in images with only two colors. Starting with 1 color and along the image there appeared more and more pixels of a different color.
Here’s another example of dithering. When you have only 256 colors available for a gradient, you’ll have to do something like this to blend from color to color.
Below is the dithering effect used on a 16bit image. On the left is the original 32bit image. The middle image is the plain 16bit version, with banding. The one on the right one dithering applied to it.
How to fix
The best way to fix this problem is to make sure your images look right. Don’t depend on the phones to fix the problem for you. I personally do not want to take the risk of any of my images looking ugly on someone’s phone. When the artwork is crap the app is probably too. Always make sure you walk the extra mile to make your apps look perfect. If a similar app looks better, people use that one instead of yours!
The easiest and free way to fix your images is to use Paint.NET with a special plugin.
After downloading and installing I’ve opened a splash screen for my app in Paint.NET. The image uses a lot of smooth transitions between colors and will look bad on some phones.
Next, go to Effects –> Photo in the menu and select Simulate Color Depth…
I’ve you did not get the earlier part about the dithering and the different bit depths, I suggest you play a little with the settings to see what’s effect of the different bit depth settings. And turn Dither on and off a couple of times to see the magic happening.
I personally use the Bayer Ordered 8×8 method on all my images. But you’ll free to use an other one if you like.
Hit Ok and you’re done.
If you are using Photoshop for your imagery, you can find an action to apply dithering to your images over at Robby Ingebretsen’s blog.
Wrap-up
Unfortunately not everyone is dithering their images, which results in bad looking apps. As you’ve seen it’s pretty simple to resolve. I hope to never see banding and ugly artifacts in applications anymore.
colorizing images using expression blend
Yesterday I recorded a screencast to demonstrate how to colorize images in a Windows Phone 7 application using Expression Blend 4. In Silverlight or WPF I use a shader to colorize images, but because shaders aren’t available in the same way in Silverlight for Windows Phone I had do come up with a different technique. In this tutorial I show how to use application bar icons as an opacity mask on rectangles. I set the fill brush of these rectangles to the default phone accent brush.
Here’s the video:
Setting visibility based on wp7 themes
Intro
The Technical Certification Requirements for Windows Phone 7 applications state the following:
5.5.2 – Content and Themes
Application content, such as text and visual elements, must be visible and legible regardless of the phone theme. For example, if the phone theme changes from black background to white background, the text and visual elements of your application must be visible or legible.
This means that everything in you application, including images, should be well visible in the dark and light theming of the phone. Handling dark/light support is very easy.
Dark and Light
Often companies have a special version of their logos for different situations (Bing for example). For this demo I’ve created two logos, a black and a white one. The white logo should be used when the theme is set to dark, the other when a light theme has been selected.
I’ve dropped these images into Expression Blend and grouped them together in a Grid control (Ctrl+G ). This grid is placed in the title panel, which resulted in the following XAML:
<StackPanel x:Name="TitlePanel" Grid.Row="0">
<Grid>
<Image Source="Logo-Black.png" />
<Image Source="Logo-White.png" />
</Grid>
</StackPanel>
To get the white logo to be only visible when the dark theme is set, select the image of the white logo. With the image selected click on the “Advanced options”-peg:

Now, go to “System Resource” and select the “PhoneDarkThemeVisibility” resource.

At this point a green rectangle is placed around the visibility property of the images letting you know a resource is set on that property.
To get the same results for the dark logo, repeat the process on that images. But select the “PhoneLightThemeVisibility” instead.
Testing
To test the results right in Expression Blend, got to the “Device” tab. On this tab you can set different device settings, including the Accent Color and the Light or Dark themes.

Switching from dark to light and back should result in the images below.

Wrap-up
Setting the visibility like this can be done on every element in your XAML. And whenever you need to use the visibility for other purposes, there’s a similar resource for the Opacity.
metro colors for photoshop
I did some designing for a Windows Phone 7 App this week. I wanted to test some graphics using the accent colors. I’ve saved the color swatches I use.
If you’re using Photoshop or Illustrator and would like to use them too, you can download them here:
Windows Phone 7 app – New Kids Button
Today my new app was published to the Windows Phone Marketplace. The application shows a big red button. When this button is pressed a quote from the movie and TV series of New Kids is played.
In this I application I wanted to try a few things. First, I wanted to see how to create a trial version of an application with possibilities to buy the app. Next I added a couple of behaviors to make it very easy to share a link to the application in various ways. The main goal of all these is ease of use for the developer and reusable. For example, a lot of times you’ll need a link to the marketplace, navigate to a URL or let the enduser write a review.
Another thing I would like to build is a localized app. The first version of this app is in Dutch only. I’m working on the German version. There will be an English version too, although this will contain the Dutch quotes.
Trial version
For the trial version of the application I wanted to show a MassageBox after a few taps on the button. The MessageBox should have a link to the marketplace to directly buy the app.
“You are using the trial version of the New Kids Button application. The full version contains more quotes!
[Buy now] [Continue trial]”
Another thing that I’ve added is a behavior that sets the visibility of the element it is applied to based on whether the application is running in trial mode or not.
Other behaviors
The first behavior continues a bit on the trial version. The behavior is used to navigate to the details of the application in the marketplace. All you need to do is place this on a button and it’s ready to go.
Because getting people to review your application is crucial to a successful app you’ll need to fire up the review task somehow. One behavior in this application does just that. Attach it to a button and it opens the review screen when it is pressed.
Sending an email from the application needs to done quite often too. A behavior that fires up the email task is used in the app. You can set the body, subject and addressee of the email.
Another behavior takes a URL as a parameter. When it is placed on a button it can be used to open a browser windows and show that URL.
The last one is my personal favorite. Sharing a link to your app on a social network is a great way to promote your application. This behavior uses the ShareThis API to share a link on a lot of different networks.
You can download this behavior here: TimmyTools.Wp7.Behaviors.zip
A few other links
Link to the app in the marketplace : http://timmykokke.com/NewKidsApp
Twitter: @NewKidsApp
Email: NewKidsApp@hotmail.com
Sounds on Windows Phone 7 – KnockOnWood
![]()
Last week my KnockOnWood Windows Phone 7 app was released in the marketplace. The basic idea of the application is that it gives you something to knock on if no real wood is available. In other words, it should play a sound effect when the screen is touched.
From Wikipedia:
Knocking on wood, and the spoken expression “knock on wood,” are used to express a desire to avoid “tempting fate” after making some boast or speaking of one’s own death.
In this application I wanted to try out to work with sounds for another application I’m working on. I had only a few requirements for this application:
- Multitouch. The sound should be triggered even if the screen is touched already.
- Fast. You should not have to wait for a sound to finish playing when you tap the screen. Just play it immediately.
Multitouch
Because of requirement 1, Multitouch, I decided to go for the static Touch class instead of using normal mouse events. To handle touches to the screen you’ll have to subscribe to the FrameReported event. I’ve added the following line to the constructor.
Touch.FrameReported += this.TouchFrameReported;
I figured a sound should only be played if a touch point is added to the screen. So I’ve created a private field _current to keep track of the number of touch points. If the first, or primary, touch point is taken off the screen (TouchAction.Up) this number should be reset to 0. If the number of touchpoints at a certain moment exceeds the stored number the sound is played.
private void TouchFrameReported(object sender, TouchFrameEventArgs e)
{
int newcurrent = e.GetTouchPoints(this.LayoutRoot).Count();
if (e.GetPrimaryTouchPoint(this.LayoutRoot)
.Action == TouchAction.Up)
{
newcurrent = 0;
}
if (newcurrent > this._current)
{
// play sound
}
this._current = newcurrent;
}
Sound
At first I thought about using a single media element to play the knocking sound. But, with the first few tests it became clear a media element isn’t fast enough. Starting, stopping, rewinding and playing again didn’t work as easy as I hoped. I had to turn over to XNA for playing sounds.
Playing a SoundEffect when the screen is touched was still not fast enough… So, I tried SoundEffectInstance, which holds an instance of SoundEffect ready to be played. This worked a lot better, but stopping, rewinding and starting an instance was not completely right. Tapping on the screen wasn’t quite right.
Because I wanted to play the sounds as fast as possible I’ve came up with the following solution. I’ve created an array of SoundEffectInstance and cycled through that on every tap. Because the knocking sound is pretty short, I’ve set the buffer size to 10 instances. This didn’t cause anything notable what tapping the screen.
Throughout the code I use a constant and two fields:
private const int BufferSize = 10; private readonly SoundEffectInstance[] _soundEffectInstances; private int _currentInstance;
In the constructor the _soundEffectInstances array is constructed and filled with instances of a SoundEffect.
this._soundEffectInstances = new SoundEffectInstance[BufferSize];
var effect = this.LoadSound("woodknock.wav");
for (int i = 0; i < BufferSize; i++)
{
this._soundEffectInstances[i] = effect.CreateInstance();
this._soundEffectInstances[i].IsLooped = false;
}
The LoadSound method takes a path and filename of a content file in the solution, reads it and returns a SoundEffect.
private SoundEffect LoadSound(string path)
{
using (Stream stream = TitleContainer.OpenStream(path))
{
return stream != null ? SoundEffect.FromStream(stream) : null;
}
}
When the screen is tapped, the TouchFrameReported event handler is called. In this method I did all the playing from the array of sound instances and keeping track of which instance to play.
private void TouchFrameReported(object sender, TouchFrameEventArgs e)
{
int newcurrent = e.GetTouchPoints(this.LayoutRoot).Count();
if (e.GetPrimaryTouchPoint(this.LayoutRoot)
.Action == TouchAction.Up)
{
newcurrent = 0;
}
if (newcurrent > this._current &&
this._soundEffectInstances != null &&
this._currentInstance < BufferSize &&
this._soundEffectInstances[this._currentInstance] != null)
{
this._soundEffectInstances[this._currentInstance].Play();
this._currentInstance++;
if (this._currentInstance >= BufferSize)
{
this._currentInstance = 0;
}
}
this._current = newcurrent;
}
Wrap-up
Playing one sound at a time without having to deal with speed and responsiveness is not that hard. Playing multiple instances is a bit harder. But, as you’ve just seen, can be done with only a few lines of code.
If you have a Windows Phone, please give the application a try and show your support by rating it. The KnockOnWood application can be found in the marketplace.
For future tutorials on Windows Phone, Silverlight and Expression Blend please subscribe to the rss feed or follow me on Twitter (@Sorskoot).
Second Windows Phone 7 app–Zwaailicht
Today, my second Windows Phone 7 app, Zwaailicht, has passed certification and is available in the Marketplace. The application shows information about emergencies in the Netherlands, based on the P2000 system. There are a couple of sites that show this information about Police, Fire and Ambulances. When you hear a siren somewhere, you can check what’s going on in the neighborhood. Or you can see what has happen in your region when you weren’t t
here.
Zwaailicht helps you choose one of the many feeds of http://www.alarmeringen.nl. Which was kindly enough to made their feeds available on a Creative Commons-license. The application gives you 4 options to base your feed on.
- City
- Region
- GPS
- Nationwide
The application contains a list with almost all Dutch cites you can scroll through. To find the city you are looking for a bit faster you can use the searchbox on top to filter the list.
The region selection is a much smaller list of the regions the Dutch emergency services work in.
Zwaailicht can also find a city based on your current GPS location. It uses the Bing Geolocation service to do this. Zwaailicht sends your current GPS location to this services which returns your current address. Zwaailicht uses the city from this address to get a new feed.
The application uses Teleriks Rad Controls for Windows Phone for navigation, showing lists and filtering them. This took away lots of work in the design of the application and added a lot of smoothness and animations.
For the design itself I choose to stick to the Metro theme as much as possible. I added a couple of backgrounds to make the application stick out a little more. I used the default animations as much as possible.
The application failed certification the first time. Besides correctly configuring the manifest file in the project to contain its capabilities, like GPS in this case, it also needed to include a privacy policy. I’ve added a this to the about screen. In this I explain the data captured from the GPS is not used for anything else that getting the current city. Added the privacy policy was enough to get it certified the second time.
The application can be downloaded here. Don’t forget to leave a review if you like it. If you don’t, please send me an email or tweet and I might add your suggestion to the next version.

