Monday, December 29, 2008

Discovering RelativeSource.PreviousData

When working with Data Binding in WPF, I have found the RelativeSource class very useful. This class is useful when you want to bind to a source relative to the binding target. For example you may want to bind the Width of a control to its Height. In this case RelativeSource.Self can be used. Or you may want to bind to an element that is an ancestor of the binding target. Here you would use RelativeSource.FindAncestor.

But there was another use of RelativeSource that I was not aware of until recently - RelativeSource.PreviousData. Let me explain where this might be useful. Say you have data bound an ItemsControl like a ListBox to a collection of data items. You have written a DataTemplate to define how each item must be displayed within the ItemsControl. Within the DataTemplate you have access to the current data item. But what if you also want access to the previous data item?

For example, you may be displaying the stock values for a company as a chart as shown below.

Each bar in the chart represents one data item within the ItemsControl. But within each item(above the bar), you also want to show the increase/decrease of the stock value when compared to the previous stock value. This is where RelativeSource.PreviousData is useful as shown below.

<DataTemplate x:Key="RecordTemplate">



<TextBlock Margin="3,0,0,3">


<MultiBinding Converter="{StaticResource RecordsDifferenceConverter}">


<Binding RelativeSource="{RelativeSource PreviousData}"/>






</ DataTemplate

In the above XAML snippet, the MultiValueConverter accepts the value of the current item and the value of the previous item, and returns the difference between the two. This is displayed above each bar in the chart.

The source code for this sample may be found here. Keep in mind that this is not a fully implemented chart – there are so many things missing. I just wanted to illustrate where RelativeSource.PreviousData may be useful.

Wednesday, October 29, 2008

Implicit Styles in Silverlight

WPF supports both explicit and implicit styles (application wide styles), while Silverlight supports only explicit styles. This means that in Silverlight when you define a style as a resource, you have to give it an explicit key, and call that key wherever you want the style to be applied. For example, if you have defined a TextBlock style in App.Resources, you have to explicity set the Style property on all TextBlocks within the application like this:

<TextBlock Text="Text1" Style="{StaticResource key1}"/>

<TextBlock Text="Text2" Style="{StaticResource key1}"/>

<TextBlock Text="Text3" Style="{StaticResource key1}"/>

This has been an issue Silverlight developers have been grappling with for a long time. The Silverlight 2 release (RTW) did not have a solution for this. Fortunately, the Silverlight Toolkit that has been released yesterday, comes with an ImplicitStyleManager that makes implicit styles possible in Silverlight. If you are not familiar with the Silverlight Toolkit, you can read about it here.

So, how do you make use of this?

1) Download the Silverlight Toolkit.

2) Copy Microsoft.Windows.Controls.Theming.dll that comes within the toolkit to your Silverlight project and add a reference to it.

3) Add a reference to the namespace within which the ImplicitStyleManager resides:

xmlns:theming="clr-namespace:Microsoft.Windows.Controls.Theming; assembly=Microsoft.Windows.Controls.Theming"

4) Now use the ApplyMode property to set implicit styling:

<StackPanel x:Name="stackPanel" theming:ImplicitStyleManager.ApplyMode="OneTime">

<TextBlock Text="Static Text 1" />

<TextBlock Text="Static Text 2" />


5) Of course, you should have defined the style somewhere in the resources collection as shown below:


<Style TargetType="TextBlock">

<Setter Property="Foreground" Value="Red" />

<Setter Property="FontSize" Value="20" />

<Setter Property="Margin" Value="5" />



Now you are good to go. The ImplicitStyleManager will ensure that the style is passed down to the TextBlock down the element tree.

If you dynamically add a TextBlock to the element tree (at run time), you will find that the TextBlock will not get the style. In this case, you will have to set ImplicitStyleManager.ApplyMode="Auto". But setting it to Auto can have a major performance impact, so use this sparingly.

There you go - implicit styles in Silverlight :).

Saturday, September 27, 2008

Silverlight 2 RCO is Out

Silverlight 2 RCO is Out! So that means that the Silverlight RTW (Release To Web) is round the corner. The RCO release is a developer-only runtime edition that will help developers to prepare their existing Silverlight 2 Beta 2 applications for the final release. Some points to note:
  • This RCO release is feature complete - so do not expect any more controls/features in the Silverlight 2 release. However more controls/features can be expected in future months to be built on top of Silverlight 2 (these will not be part of the core runtime).

  • Three new controls added - ComboBox, ProgressBar, and PasswordBox. These along with most other controls will be part of the Silverlight runtime (which means that these will not be needed to be downloaded with the Silverlight application).

  • The Silverlight runtime is still only 4.6MB in size.

  • The default control styles/templates have been modified.

  • Once Silverlight 2 is released, users with existing beta releases installed will automatically be upgraded to use the final version (also developer machines with RCO , I suppose).

  • A modal dialog MessageBox is now available.

  • System.Windows.Controls.Extended.dll renamed to System.Windows.Controls.dll

  • If you are using custom controls, remember that generic.xaml is now expected in the 'themes' folder rather than at the root of the project.

Saturday, August 30, 2008

Silverlight on the Desktop

Its been almost two months since I blogged - just haven't had the time. But tonight I just couldn't resist making this post. My brilliant colleague at IdentityMine, Sameer Thiruthikad has been spearheading work on an exciting Silverlight utility called Desklighter, and the Beta is now public.

What is the Desklighter? Well, ever wished you could package your Silverlight application into an stand alone executable that could work offline? That is precisely what the Desklighter enables you to do. Read the whole story here, and be sure to try it!

Wednesday, June 4, 2008

What's New In Silverlight 2 Beta 2?

Silverlight 2 Beta 2 was announced in TechEd earlier this week. The actual bits are not yet public, but I think it should be soon.
(Update: The Beta 2 bits are now available. Scott Gu has a detailed list of changes here)

The best news for me was that there are several changes for making the Silverlight model as close as possible to the WPF model. This is very important for Silverlight to live up to its reputation of being a WPF subset (remember its code name WPF Everywhere? )

Below are some changes:

  1. Improved Templating model using the Visual State Manager
  2. New Tab Control
  3. DataGrid improvements: Autosize, Reorder, Sort, Performance increase
  4. TextBox: Text wrapping and multiline selection highlighting in textbox.
  5. Includes the Visual Tree Helper.
  6. DataBinding: Binding to attached properties is now supported.
  7. Controls like the DataGrid which are now not part of the runtime (and have to be downloaded as part of the XAP) have been moved to the runtime. This is good news, but then the XAP is going to be heavier :).
  8. DeepZoom: XML based file format
  9. Full Screen Mode keyboard support: The only key supported earlier was escape. This was supposed to be for security reasons. Now additional keys are supported (arrow, tab, enter, home, end, pageup/pagedown, space).
  10. A bunch of new stuff on the Networking side: Upload support for WebClient, ability to allow user to increase Isolated Storage capacity (via UI), duplex communications ("push" from Server to client), new VS template for “Silverlight-enabled WCF Service”.
To see a full list of changes see this post.

Tuesday, June 3, 2008

Microsoft Innovation Days, Kochi

Microsoft India has been holding events around the country to get people excited about some of the newer technologies. Last week, an event was held at Kochi (Cochin) called Microsoft Innovation Days. One of the sessions was on Silverlight. Since IdentityMine has been into this technology for more than a year, we were invited to present a 30 minute part. I did the presentation on behalf of IdentityMine, and it was a great experience talking to the 200 odd developer crowd!

During the presentation, I showed a demo of a Silverlight 2 application we created. This was an application (not a full fledged one) that was created in just about a week's time. The short time period surprised a lot of people!

I discussed briefly some of the features used in the Silverlight demo - like Databinding, Templates, Animations, Drag and Drop, Video Brush, Isolated Storage, and Video Markers. I also shared some of our experiences working with Silverlight, including the Developer-Designer workflow. My session ended with a fun example of using templates - I had ported the 'Button Fish' (of Avalon Feature Fest fame) to Silverlight

I think we had a lot of people excited about Silverlight. Many in the audience later expressed their desire to try out Silverlight.

Sunday, May 11, 2008

Assemblies in the Silverlight Runtime

  • Details in this post apply to Silverlight 2 Beta 1, and may change in future Silverlight versions.
  • You may want to read my previous post to get a better understanding this post.

Say you have a Silverlight application with a Canvas and a ListBox. Both these controls belong to the same namespace System.Windows.Controls. Will these controls be downloaded as part of this particular application's xap, or will this be part of the Silverlight runtime installed initially by the user?

The answer is interesting: As far as Silverlight 2 Beta 1 is concerned, the Canvas is within the System.Windows.dll which is part of the Silverlight runtime and hence will not be downloaded to the client along with the xap. However, the ListBox is within the System.Windows.Controls.dll which is not included in the Silverlight runtime. So this will be downloaded with the xap package.

This also means that if you are creating a custom splash screen then you can use the Canvas within it, but not the ListBox since the splash screen will show before the xap has been downloaded.

Friday, May 9, 2008

Namespaces and Assembly Names

Note: Details in this post apply to Silverlight 2 Beta 1, and may change in future Silverlight versions. The basic idea though remains the same.

A Silverlight developer recently reported this problem. He wanted to use the Silverlight DataGrid in his application. He knew that the DataGrid is a part of the assembly System.Windows.Controls.Data.dll. So he added a reference to this assembly in his Silverlight project. So far so good.

Next he tried to import the namespace by typing in "using System.Windows.Controls.Data" so that he could start using the DataGrid. Now here started the problem. Visual Studio refused to recognize this namespace. Was this a bug in Silverlight, or perhaps in Visual Studio?

Neither. It is true that the DataGrid resides in the assembly System.Windows.Controls.Data.dll; but it is still part of the SystemWindows.Controls namespace just like the other controls in Silverlight.

Let us look at some other examples. The TextBlock, Canvas and Grid too belong to the System.Windows.Controls namespace but they actually reside in the assembly SystemWindows.dll not in SystemWindows.Controls.dll.

By the way, the ListBox is one control that belongs to the namespace System.Windows.Controls and resides in an assembly with the same name.

Simple, but interesting , huh?

Wednesday, April 30, 2008

Testing Silverlight Streaming

If you are reading this blog, you certainly know about the Silverlight streaming service. But did you know that you can stream not just media but an entire Silverlight application? That's right, you can upload your Silverlight application to the Silverlight streaming server, and they take care of the rest. The video and button you see on this page are from a simple test app I uploaded to the server. All you need to do is just paste the html code they provide you after you upload your application.

Want to try this out? This post by Tim Sneath is a great place to start!

Friday, April 25, 2008

Using the WebClient to Download Content On-Demand

Source (Beta 2): The Beta 2 source is available here.

In this post I'm going to describe how you can use the WebClient class in Silverlight 2 to download content on-demand.

Firstly why would you want to download something on-demand? Say your application is displaying images, video, lots of XAML etc. Now if you allow the appplication to download all of this initially to the client, the user may get impatient because of the long waiting period. You may lose your user even before he has had a first look at your application.

So it makes sense to only include in the initial download, what is absolutely essential for the application to load. Once the application is loaded, you can start downloading other parts of the application behind the scenes. This is where downloading content on-demand comes into picture.

We'll look at three scenarios.

  1. Downloading a loose image file on-demand.

  2. Downloading a zip file on demand and retrieving an image file.

  3. Downloading an assembly on demand, and thereafter using classes within the assembly

The source for the sample application I created to illustrate this is available here.

Downloading a loose image file on-demand

In Silverlight 1.0, the class used for downloading content on-demand was the Downloader class. In Silverlight 2, we use the WebClient class.

private void Button_Click_1(object sender, RoutedEventArgs e)


WebClient wc = new WebClient();

wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted1);

wc.OpenReadAsync(new Uri("bird.jpg", UriKind.Relative));


void wc_OpenReadCompleted1(object sender, OpenReadCompletedEventArgs e)


if (e.Error == null)


StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);

BitmapImage imgsrc = new BitmapImage();


ImgToFill.Source = imgsrc;



This code is quite self-explanatory. You need to call the OpenReadAsync method ofthe WebClient, and then retrieve the image in the OpenReadCompleted event.

Downloading a package (zip file) on-demand and extracting an image file

In this case the code is similar.

To download a package
  1. Copy zip next to xap file
  2. Download as stream using WebClient
  3. Use StreamResourceInfo class to retrieve the desired part from the package stream
private void Button_Click_2(object sender, RoutedEventArgs e)


WebClient wc = new WebClient();

wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted2);

wc.OpenReadAsync(new Uri("", UriKind.Relative), "Garden.jpg");


void wc_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)


if (e.Error == null)


StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);

String sURI = e.UserState as String;

StreamResourceInfo sri2 = Application.GetResourceStream(sri, new Uri(sURI, UriKind.Relative));

BitmapImage imgsrc = new BitmapImage();


ImgToFill.Source = imgsrc;



Notice that after downloading the zip package, we did not have to unzip it explicitly. The StreamResourceInfo class took care of that.

Downloading an assembly on-demand and extracting an image file

What do we mean by downloading an assembly on-demand? Say you a large assembly that contains content like user controls, XAML etc. that you want to use in the application, but not in the first page that the application loads.

In this case you you can download the assembly on-demand instead of loading it at the beginning when the application is loaded by the client.

One question I had when I read of this concept was, wouldn't you have to reference the assembly in the application at design time itself to compile code that makes of its classes? And if you reference the assembly, won't it become part of the application's initial download to the client?

Yes, it is true that you need to reference the assembly, but you set the private attribute of the csproj file for that assembly to false. In this case, the assembly will not become part of the xap package, but you can still call classes of this assembly in the code base.

<ProjectReference Include="..\LargeSizeAssembly\LargeSizeAssembly.csproj">





Summarizing the steps, this is what you need to do:
  1. Add reference to the assembly
  2. In the csproj file:set the 'Private' tag for that assembly to False
  3. Copy assembly next to xap file
  4. Download as stream using WebClient
  5. Use AssemblyPart class to load assembly to current AppDomain
  6. Now start using classes in the assembly

private void Button_Click_3(object sender, RoutedEventArgs e)


// Download assembly "on-demand"

WebClient wc = new WebClient();

wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted3);

wc.OpenReadAsync(new Uri("LargeSizeAssembly.dll", UriKind.Relative));


void wc_OpenReadCompleted3(object sender, OpenReadCompletedEventArgs e)


if (e.Error == null)


//Uncommenting the line below will throw an exception because the assembly

//in which Page2 resides has not been loaded into current AppDomain as yet

//Page2 page2 = new Page2();

// Convert the downloaded stream into an assembly that is

// loaded into current AppDomain

AssemblyPart assemblyPart = new AssemblyPart();


//now access classes in the downloaded assembly




private void DisplayPageFromLibraryAssembly()


// Instantiate type from assembly

Page2 page2 = new Page2();

// display it



You can see how powerful this option of downloading on-demand is. The source for the sample application I created to illustrate this is available here.

Tuesday, April 22, 2008

XAMLPad for Silverlight

XAMLPad is a tool for WPF that ships with the Windows SDK, and allows you to easily parse and render XAML snippets. As far as I know XAMLPad for Silverlight is not available as yet. However, Robby Ingebretsen who also works for IdentityMine has added Silverlight support to his Kaxaml tool. After you launch Kaxaml, you can open a new tab either in WPF, or in Silverlight.

By the way, this tool has been created in WPF. Really cool!

Detecting Screen Width and Height from within a Silverlight app

There are no direct API's that allow you to detect the screen width and height from within a Silverlight plug-in. But this post by Ashish Shetty tells you how to do this.

Friday, April 18, 2008

Differences between the WPF and Silverlight 2 model

What are the differences between the WPF and Silverlight 2 model? If you have worked with WPF before you started working with Silverlight (like me!), then this is no doubt a key question lingering in your mind. I understand that Microsoft is planning to publish such a list, and that would be great when it comes. But until that is published, below is a list of differences that I have picked so far. Remember this is a comparision between WPF and Silverlight 2 Beta 1. Some of the gaps between these two related technologies may be filled in future releases of Silverlight.

The observations below are what apply to Silverlight 2 Beta 1.

  • Once you apply a style to a FrameworkElement, you cannot reassign a new style. This is bad news because this means that the user cannot pick a theme. Having said that, you can still reassign properties that have been once assigned. This means that you can reassign the control template since it is a property as well.
  • Styles cannot inherit from other styles - the 'BasedOn' property cannot be used.
  • Styles have to be referenced by a key. This means that you cannot drop a style for a button in your 'application.resources' hoping that all buttons in the application will pick up the style. You need to explicitly reference it by its key in all buttons in the application. Sigh!


See my earlier post on this. There are no triggers in Silverlight Beta 1 for styles, control templates and data templates. Sigh, sigh and more sigh!

Say you are changing the control template of a button. When doing that, as part of the template you would want to define an animation that should fire when the mouse is over it. In WPF, you would just add a trigger in the control template that looks for the IsMouseOver property - which is a neat way of doing things. But in Silverlight, the developer who creates the control has to create event handlers for the MouseEnter and MouseLeave events, and in these event handlers he has to load storyboards with well known names. Then hope that the designer/developer skinning the control will supply storyboards with the same names!

Control Templates

Keeping aside the limitation control templates have that I explained above (in the triggers section), I think this is one area that Silverlight is better than WPF. Silverlight follows the parts model. This means that any control (controls that ship with Silverlight and custom controls) publish a well defined control contract. This control contract will define

  1. the minimum UIElements (and their names) that should be present in a control template for that control
  2. the storyboards (and their names) that should be present.

So this means that a designer/developer who is going to skin (or define a new control template for) the control needs to only look at the control contract to understand what the control expects to function properly.

In WPF, you have to search for the "PART_" prefix in the default control template. There is no well-defined control contract. I understand from the MIX talks that this is one area that WPF, the big brother, will listen to Silverlight and emulate it in future WPF releases.

Also, a custom control in Silverlight cannot inherit from UIElement or FrameworkElement classes though these classes are present (by the way, there is no Visual class in the class hierarchy in Silverlight). Custom controls should extend the Control class, or other classes like TextBox or Button that extend the Control class.

What makes skinning a control (read changing its control template) really complicated now is that at the moment Blend does not support templating. I'm sure that is coming. But until then, your XAML editing skills will be put to the test!


Dynamic resource references are not available. All are static references.

Data Binding

The following apply to Silverlight 2 Beta 1:

  • No binding the property of a UI control to the property of another UI control. There is no 'ElementName' property in the binding syntax.
  • No 'RelativeSource'
  • No 'OneWayToSource' - who needed it anyway?
  • No UpdateSourceTrigger property. All updates to the source (for two way binding) happen immediately, except in the case of TextBox in which case changes are propogated to the source when the focus is lost.
  • Cannot bind directly to XML data. Need to convert the XML to CLR objects, and then bind to the CLR object.
  • No ReadOnlyObservableCollection. Fortunately, the ObservableCollection is available which is more important.
  • No CollectionView for sorting and filtering.
  • No validation rules.
  • No DataTemplateSelector for dynamically selecting data templates based on data.
  • No XMLDataProvider and ObjectDataProvider.


  • Commands and input bindings are not available in Silverlight 2 Beta 1.

These are a few things I observed about Silverlight 2. I plan to keep this list updated so that this will be a ready reference for someone looking for the differences between the WPF and Silverlight 2 model.

Friday, April 11, 2008

Debugging not working for your Silverlight project?

If you are bugged by the fact that debugging does not work for your Silverlight project, make sure that 'Silverlight' has been checked as one of the debuggers in the 'Start Options' of your project properties.
Happy debugging!

Thursday, April 10, 2008

Understanding Application Resource Files

First let me mention that the word "resources" is used in two contexts in Silverlight (and WPF). The main usage refers to styles, templates etc. that are reusable resources. The other usage is for referring to application resource files like images, videos etc that are used by the application. This post is about the latter.

When you add such resources to a Silverlight application you can set their build action mainly in three ways: Resource, Content or None.

In the example on the left, I have added 3 images - one as Resource, the second as Content and the last as None.

What happens to these images when the application is compiled? The image assigned as Resource (Bread.png) gets embedded into the Silverlight application assembly. So this image is not seen in the screenshots below. The image assigned as Content (Burger.png) is not embedded into the application assembly but nevertheless gets packaged into the .xap file. (Remember that the .xap file is basically a zip file renamed with .xap extension . This zip file contains the application assembly as well as other Content resource files.) The image assigned as None (Watermelon.png) is a loose resource file and so is outside the .xap package.
The screenshots below should be helpful to visualize this.

Ths screenshot is of the client bin. You can see the .xap package and the image marked as None. This resource can act as an on-Demand resource file, and so will not be downloaded initially to the client machine. It will be downloaded only when the user navigates to the page that displays this image.

When the .xap package is unzipped, you get the files shown in the screenshot on the left. You can see that the image marked as Content is part of the unzipped contents. The image marked as Resource is embedded with the application assembly (ResourceFiles.dll) and hence cannot be seen in this screen shot.

How should one refer to these resources in the XAML? And when would one prefer to use one type of build action over the other? This MSDN article explains this thoroughly. Also, this post by Ashish Shetty.

You can find the sample application I described above here (updated to Beta 2).

Wednesday, April 9, 2008

XAML Tip - How do I escape curly braces?

Ever wondered how you would get a TextBlock to display some text with the curly braces? For example, say you wanted to display the text {Hello}. If you just say, <TextBlock Text="{Hello}"/> you will not get the desired result since the parser will assume that it is a markup extension.

This is what you should do to trick the parser: <TextBlock Text="{}{Hello}"/>

Simple, eh?

Sunday, March 30, 2008

We told you so!

Last December, we at IdentityMine did a Silverlight 1.0 training at Mumbai and Bangalore in which we had a wonderful audience - a total of more than 50 from various companies around India participating. Though the training was primarily on Silverlight, we also covered some 'then-WPF-only concepts' like Styles, Templates and Data Binding.

While most of the feedback was very positive, I still remember a few questioning the rationale behind including these "WPF concepts" in a Silverlight training session. Of course, the reason was, as we mentioned during the course, that these concepts would be included in Silverlight 2 later. And included they are! I'm sure they now realize that they have had a great sneak peek into these important concepts months ahead of the Silverlight 2 Beta release.

We told you so!

Friday, March 28, 2008

Silverlight Spy - 'Snoop for Silverlight'

Those who have worked in depth with WPF know what a valuable tool Snoop is. It allows you to see the visual tree of a WPF application, change values, track events and much more! Just the other day I was thinking how good it would be if we had a 'Snoop for Silverlight'.

I recently discovered Silverlight Spy, which does just that. You can snoop into the visual tree of any Silverlight 2 application. Before you install it, make sure you have installed the pre-requisites, escpecially the web browser control that it needs to stream the web content.

Happy spying!

Thursday, March 27, 2008

No Triggers in Silverlight 2 Beta!

Being a WPF developer, I have been hoping that the Silverlight model would resemble WPF closely. After all, Silverlight is supposed to be a 'subset' of WPF (remember the code name for Silverlight was WPF/E - 'WPF Everywhere').

Now that Silverlight 2 Beta is out, I have been looking at it very closely. As expected a lot of features are common to WPF - styles, templates, databinding etc. But what on earth happened to triggers? Triggers are missing! C'mon Microsoft don't tell us there are no triggers in Silverlight. I'm hoping that triggers will arrive before the final release of Silverlight.

By the way, let me clarify that when I say that there are no triggers in Silverlight 2 Beta 1 what I mean is no triggers where they matter most - in styles, control templates and data templates. The FrameworkElement class does have a trigger collection, but that is not very useful is it, without triggers in styles and templates?

Update: For a full discussion on the differences between the WPF and Silverlight 2 model, see this post.

Also enjoy this geeky duel on the new Silverlight templating model (sans triggers) between two of my esteemed colleagues at IdentityMine - Robby Ingebretsen and Dr. WPF.

Joining the Bandwagon!

Finally... I decided to blog!

I plan to blog on my experiences with WPF and Silverlight, technologies that I currently work on and ones that I have come to love. I work with IdentityMine at their Kochi office in India, and that means that I've had plenty of opportunities to do a lot of interesting work with these technologies. I have been working with WPF for over two years and Silverlight for about a year. Recently, I was also privileged do some corporate training in WPF and Silverlight for other software firms in India, and that was an experience I really enjoyed.

Hope you enjoy reading my blog!