During an interesting event last week, discussing the virtues of Silverlight apps out of the browser, I was confronted with Behavior. I should probably be ashamed because I never heard of them before. Because they have a high coolness- and awesomeness-level I checked if they were also available for Windows Phone, and hooray, they are!
Now what are they about ? In WPF you can use Triggers, to react on certain "events", like this one :
<Button.Triggers>
<EventTrigger RoutedEvent="Click">
<BeginStoryboard Storyboard="{StaticResource mySB}"/>
</EventTrigger>
</Button.Triggers>
Specially useful when you're creating your own Controltemplates. Unfortunately they're not available in Silverlight (except for the Loaded-event). When creating your own controls, and you need them to have some kind of visual feedback, we'll have to use the Visual State Manager.
In my little example I have a WP7-app that regularly calls a "Distance-service" that gives the shortest distance between you and your geographically closest friend (could be something Foursquare provides). The closest distance will be shown by some small colored ellipse. Whenever the distance changes, the color changes.
Let's start by the service: I have a little WCF library that I'm hosting in a WPF-app. Service looks like this:
public class DistanceService : IDistanceService
{
public double GetDistance()
{
return DistanceHelper.Distance;
}
}
Can't make them smaller than this. What about this DistanceHelper ?
public static class DistanceHelper
{
private static double distance=10;
public static double Distance
{
get { return distance; }
set { distance = value; }
}
}
My MainWindow only has a slider going from 0 to 10, with an eventhandler for the ValueChanged. In this eventhandler I simply set the DIstance-property from DIstanceHelper:
1: private void distanceSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
2: {
3: DistanceHelper.Distance = distanceSlider.Value;
4: }
5:
6: private void Window_Loaded(object sender, RoutedEventArgs e)
7: {
8: host = new ServiceHost(typeof(DistanceServiceLib.DistanceService));
9: host.Open();
10: }
11:
12: private void Window_Unloaded(object sender, RoutedEventArgs e)
13: {
14: host.Close();
15: }
I also configured my WCF-service to use simple basicHttpBinding.
In my WP7-app I start by creating a service reference towards my service. This will be used by a helper-class DistanceReader:
1: public static class DistanceReader
2: {
3: static DistanceReader()
4: {
5: DispatcherTimer timer = new DispatcherTimer();
6: timer.Interval = new TimeSpan(0, 0, 10);
7: timer.Tick += (s, ea) =>
8: {
9: var proxy = new DistanceServiceRef.DistanceServiceClient();
10: proxy.GetDistanceCompleted+=(s2,ea2)=>
11: {
12: DistanceReader.LastDistance = ea2.Result;
13: };
14: proxy.GetDistanceAsync();
15: };
16: timer.Start();
17: }
18:
19: public static event EventHandler<DistanceEventArgs> DistanceChanged;
20:
21: public static void OnDistanceChanged(DistanceEventArgs e)
22: {
23: if (DistanceChanged!=null)
24: {
25: DistanceChanged(typeof(DistanceReader), e);
26: }
27: }
28:
29: private static double lastDistance;
30: public static double LastDistance
31: {
32: get { return lastDistance;}
33: set
34: {
35: if (lastDistance!=value)
36: {
37: lastDistance = value;
38: OnDistanceChanged(new DistanceEventArgs() { Distance=value});
39: }
40: }
41: }
42: }
This class calls the service (every 10 seconds) and raises an event whenever the distance changes. Now, how to show this ? Let's start by the VSM-approach. But that is something I'll leave for part 2.
Tweet

While experimenting with push notifications for updating your live tiles, I found the ShellTileSchedule-class. It sounded interesting enough to play around with it.
On MSDN I found following description for this class : Creates an object which allows an application to schedule updates of its tile's background image. The ShellTileSchedule has some properties like the recurrence and the interval. The interval is an enumeration which goes from hourly to monthly :
Another Property is the RemoteImageUri. Because of the word "Remote" I assume that the image has to be remote (that was a hard one ). So for testing this thing I first set up a website, with simply a png-image (62*62 – I copied Background.png and changed it a bit with Paint). Let's set up our schedule. This has to be done in the Application_Launching:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
sts = new ShellTileSchedule();
sts.Interval = UpdateInterval.
sts.Recurrence = UpdateRecurrence.Interval;
sts.RemoteImageUri = new Uri(String.Format("http://localhost:51177/Site/Tiles/1.png", TileNr.ToString()));
sts.Start();
}
After starting the application I had to wait for an hour before my tile changed. Changing the clock settings didn't do the job either, but after an hour, finally the tile changed.
This could be useful for pulling tiles, instead of pushing. Get a tile every hour for showing the weather conditions in your area.
Now about this "Remote"-thing. Can I use a local png-file for changing the tile this way ? My first try was to add a png-file, and than refer to it this way:
sts.RemoteImageUri = new Uri("/LocalTile/5.png",UriKind.Relative);
That was not good.
Also tried it with "/TilesTest;component/LocalTile/5.png", but also no success. I needed to get the absolute path. In Silverlight I can use App.Current.Host.Source and Windows Phone is Silverlight, right. But I cannot use the Source-property here, although I can see it in my Locals-window:
OK, another try : let's use this code:
Uri uri = new Uri(new Uri(
"file:///Applications//Install//27F6C4CB-1192-44AD-A970-635F12689A08//Install"),
"//LocalTile//5.png");
sts.RemoteImageUri = uri;
OK, I know it's not very useful, because every user that has this application, will also have another GUID. Still : I do it for serving science . Result :
What happened to my GUID and stuff jQuery152010964315148992043_1315308924440 Last try, Let's simplify by using this :
Uri uri = new Uri(
"file:///Applications//Install//27F6C4CB-1192-44AD-A970-635F12689A08//Install//LocalTile//5.png");
And now I get this :
OK, I quit. Remote indeed means Remote.
Tweet

Something that will also be discussed during the upcoming Windows Phone course, here at U2U, is the cooperation between Silverlight for Windows Phone and XNA.
At the end of my previous blog post, I was left with one more challenge: saving my modified picture to the Pictures Hub. Until shortly I thought that the only way of using the Pictures Hub was through the PhotoChooserTask or the CameraCaptureTask. Luckily I came across the MediaLibrary-class from the XNA-framework, who gives much more possibilities for accessing your pictures.
To start I needed to add a reference to Microsoft.Xna.Framework. This results in an alarming message :
At first I tried to do some experimenting with the MediaLibrary. Let’s start by simply getting the number of pictures I have on the emulator :
ml = new MediaLibrary();
nrOfPics = ml.Pictures.Count;
MessageBox.Show(nrOfPics.ToString());
That works nice. The Medialibrary has several collection I can use, like Pictures, Songs, Genres,…
Next step : lets create a little slideshow-app for iterating through my pictures. I start out with a simple page :
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="523*" />
<RowDefinition Height="84*" />
</Grid.RowDefinitions>
<Image Name="image1" Stretch="Fill" />
<Grid Grid.Row="1" Name="grid1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Content="&gt;&gt;" Grid.Column="1" Name="btnGoForward"
Click="btnGoForward_Click" />
<Button Content="&lt;&lt;" Name="btnGoBack" Click="btnGoBack_Click" />
</Grid>
</Grid>
The code looks like this :
1: public partial class MainPage : PhoneApplicationPage
2: {
3: int nrOfPics;
4: int picNr = 0;
5: MediaLibrary ml;
6: BitmapImage img = new BitmapImage();
7:
8: // Constructor
9: public MainPage()
10: {
11: InitializeComponent();
12: }
13:
14: private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
15: {
16: ml = new MediaLibrary();
17: nrOfPics = ml.Pictures.Count;
18: MessageBox.Show(nrOfPics.ToString());
19:
20: ShowImage();
21: }
22:
23: private void ShowImage()
24: {
25: img.SetSource(ml.Pictures[picNr].GetImage());
26: image1.Source = img;
27: }
28:
29: private void btnGoBack_Click(object sender, RoutedEventArgs e)
30: {
31: if (--picNr<0)
32: {
33: picNr = nrOfPics - 1;
34: }
35: ShowImage();
36: }
37:
38: private void btnGoForward_Click(object sender, RoutedEventArgs e)
39: {
40: if (++picNr>=nrOfPics)
41: {
42: picNr = 0;
43: }
44: ShowImage();
45: }
46: }
Let's now return to the application created during my previous blog post. In the "Save Img" code we opened another page that simply showed the image with copyright-message. Let's now change the loaded-event of the WrittenImage-page so we can save the image :
WriteableBitmap bmp = PhoneApplicationService.Current.State["bmp"] as WriteableBitmap;
writtenImage.Source = bmp;
MediaLibrary ml = new MediaLibrary();
Stream stream = new MemoryStream();
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
ml.SavePicture("u2uPic.jpg", stream);
MessageBox.Show("Picture Saved...");
The SaveJpeg-method from WritableBitmap gives me a Stream containing the image in jpg-format. SavePicture saves the image in the MediaLibrary. However: it doesn't work ! It took me some time to find out why: It seems that the position of the stream remains at the end-position. Insert this line of code just before the SavePicture-call to make it work:
stream.Position=0;
It's working !! Cool.
Next step: let's deploy these two apps to my device and test. Not working ! How the hell is that possible ? Retesting in the emulator : works fine. Retesting on device: not working. Aaaaargh !! Disconnecting my device, going over to a colleague to ventilate my frustration and see that all of a sudden it is working !! Seems that for this thing to work, it needs to be disconnected from the PC.
Tweet

Prism 4.0, Managed Extensibility Framework, and Silverlight 4.0 provide an ideal combination to develop robust and flexible enterprise applications. This article explains how you can keep the Prism module catalog in such an application on the server side. In most of the Prism Quickstarts, the module catalog is embedded in the shell:
The application class starts the bootstrapper:
private void Application_Startup(object sender, StartupEventArgs e)
{
ApplicationBootstrapper bootstrapper = new ApplicationBootstrapper();
bootstrapper.Run();
}
The bootstrapper builds the catalog from the local file:
protected override IModuleCatalog CreateModuleCatalog()
{
ModuleCatalog catalog = Microsoft.Practices.Prism.Modularity.ModuleCatalog.CreateFromXaml(new Uri("Prism.Sample.Shell;component/Modules/ModuleCatalog.xaml", UriKind.Relative));
return catalog;
}
Unfortunately, this setup requires a rebuild and a redeploy of the shell application whenever a change in the catalog is needed (e.g. to add an extra module, or to remove a buggy module). In most -if not all- real-world scenarios it makes more sense to place the catalog in an area that allows easy modification. The following solution has the catalog in a file on the server side, but you can easily go for other storage locations, like a database table, a WCF service or a SharePoint list. Here's where the file is kept:
The bootstrapper gets an extra constructor that takes a stream:
private Stream stream;
public ApplicationBootstrapper(Stream stream)
{
this.stream = stream;
}
This stream is used to build the catalog:
protected override IModuleCatalog CreateModuleCatalog()
{
ModuleCatalog catalog = Microsoft.Practices.Prism.Modularity.ModuleCatalog.CreateFromXaml(this.stream);
return catalog;
}
On application startup, the file is read, wrapped in a stream, and handed over to the bootstrapper:
private void Application_Startup(object sender, StartupEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += this.Client_OpenReadCompleted;
client.OpenReadAsync(new System.Uri(@"Modules\ModuleCatalog.xaml", System.UriKind.Relative));
}
private void Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
ApplicationBootstrapper bootstrapper = new ApplicationBootstrapper(e.Result);
bootstrapper.Run();
}
The following two projects demonstrate both approaches. The application is a small Prism-MEF-Silverlight tutorial application that I wrote a couple of months ago. Here's how it looks like:
Here's the project before and after the modification (it contains the Prism dll's, so you might need to unblock these):
Catalog in the Shell xap: U2UConsult.Prism.Sample.Application.1.zip (1,99 mb)
Catalog on the server: U2UConsult.Prism.Sample.Application.2.zip (1,03 mb)
Enjoy !

In this short article I'll show you how to transform a resource dictionary with colors, brushes, styles and templates into a real theme - à la Silverlight toolkit themes - and how to apply it to a region in the user interface. I'll build a theme called Glass.
Building the theme
Each Silverlight toolkit theme is nothing more than a resource dictionary wrapped in ... er ... a wrapper and compiled as a separate dll. I you want to roll your own, you first create a class library project. The project will contain lots of references, lots of XAML, and just a couple of lines of C#. It will eventually look like this:
Create a resource dictionary named theme.xaml and stuff all the artefacts that your designer created - or that you downloaded somewhere - into it. Then create a very thin wrapper class around the resource dictionary. The class should inherit from the toolkit's Theme class:
Just like in the toolkit themes, it makes sense to use System.Windows.Controls.Theming as namespace.
Here's the whole code for that class:
/// <summary>
/// Implicitly applies the Glass theme to all of its descendent FrameworkElements.
/// </summary>
public partial class GlassTheme : Theme
{
/// <summary>
/// Stores a reference to a Uri referring to the theme resource for the class.
/// </summary>
private static Uri ThemeResourceUri = new Uri("/System.Windows.Controls.Theming.Glass;component/Theme.xaml", UriKind.Relative);
/// <summary>
/// Initializes a new instance of the GlassTheme class.
/// </summary>
public GlassTheme()
: base(ThemeResourceUri)
{
}
}
We're done building the theme. Now it's time to test it.
Applying the theme
All you need to do to statically apply a theme to a region in the user interface, is dropping it in the XAML:
<customtheme:GlassTheme>
<!-- Your controls here. -->
</customtheme:GlassTheme>
To test a new theme, I created a small test application with controls from different sources: a handful of native Silverlight controls, some SDK controls and a pinch of Toolkit controls. It's actually a lightweight version of one of the zones from the Silverlight Samples page. Just select Theme Browser over there to get the full page. My version is a little more compact. It looks like this:
With a simple right-click you can dynamically change the theme.
Here's how the Glass theme looks like in the test container:
The test container also applies the selected theme through XAML, but it uses the common base class to set the appropriate ThemeUri:
<toolkit:Theme x:Name="ThemedRegion"
ThemeUri="/System.Windows.Controls.Theming.Glass;component/Theme.xaml">
<!-- Your controls here ... -->
</toolkit:Theme>
After selection, a new theme is programmatically applied like this:
themedRegion.ThemeUri = new Uri("/System.Windows.Controls.Theming." + this.themeName + ";component/Theme.xaml", UriKind.RelativeOrAbsolute);
Source code
Here's the glass theme and its test container: U2UConsult.Silverlight.ThemeBuilder.zip (2,34 mb)
Enjoy!