This article is part 2 of 4 in a series attempting to cover everything I think is worth knowing about styles in Silverlight 4. The previous article in the series was Styles in Silverlight: an Introduction that covered what styles are, how they can be defined and some of their limitations.
This article focuses on some more advanced topics that are handy when building more complex applications: re-using the same styles for different types, style inheritance, style precedence and style setter precedence.
Re-Using Styles for Different Types
As discussed in the previous article, all Style elements need to specify a TargetType that specifies the type of class they need to be applied to. If an application uses several different types of visual elements, this can result in having to specify different styles again and again. Let’s say for example our application has an Ellipse and a Rectangle and we want to have both of them have a blue fill. The straightforward way of doing this using Styles is declaring two different styles for each of them and applying those using StaticResources in XAML:
However in this particular case it’s possible to combine these styles as Ellipse and Rectangle inherit from the same parent class: Shape. The Fill property that we are setting in the styles is defined in Shape, so we can define a single style with the TargetType set to Shape, then apply this Style to the elements:
So the TargetType of the style does not necessarily have to be the type of the visual element itself. It can be a parent class of the visual element if the setters within this style only refer to properties of this parent class. The XAML code for the second example is shorter, at the same time both examples look the same:
This article is part 1 of (planned) 4 in a series attempting to cover everything I think is worth knowing about styles in Silverlight 4.
What are Styles?
Styles in Silverlight are a powerful mechanism that allow controlling the visual representation of elements in a unified way for all user interface elements. The concept is similar to using CSS to control the look and feel of HTML.
Style properties differ by element type. For example on a TextBlock (a text element) one can style the FontSize, FontFamily, Foreground and lots of other properties. On an Ellipse however none of these properties can be set, on the other hand it does provide for example the Fill property, that the TextBlock does not. So creating a blue “Hello, World” text and a red ellipse could be done the following way:
<stackpanelOrientation="Vertical"><textblockFontSize="16"FontFamily="Comic Sans MS"Foreground="Blue">Hello, World!</textblock><ellipseFill="Red"Width="30"Height="30"/></stackpanel>
However, to do the same thing, we could simply define Styles. Styles are list of property-value pairs. Creating the same blue text and red ellipse with styles would be done the following way:
<usercontrol .Resources><stylex:Key="CustomTextBlockStyle"TargetType="TextBlock"><setterProperty="FontSize"Value="16"/><setterProperty="FontFamily"Value="Comic Sans MS"/><setterProperty="Foreground"Value="Blue"/></style><stylex:Key="CustomEllipseStyle"TargetType="Ellipse"><setterProperty="Width"Value="30"/><setterProperty="Height"Value="30"/><setterProperty="Fill"Value="Red"/></style></usercontrol><stackpanelOrientation="Vertical"><textblockStyle="{StaticResource CustomTextBlockStyle}">Hello, World!</textblock><ellipseStyle="{StaticResource CustomEllipseStyle}"/></stackpanel>
As you can see properties that we’ve specified as attributes on the elements, we’ve listed in the styles and then applied this style to the element. So instead of defining FontSize=”16″ of the TextBlock, we’ve added a Setter that had FontSize set as it’s Property and 16 as it’s Value. (Download the source of this example here: What Are Styles.zip)
Having seen a simple example of using styles, let’s look a little bit deeper in to what they actually are. Read the rest of this entry »
A month ago Kwwika, a real-time data streaming service provider annonced a competition to build a mash up that uses their World Cup 2010 Twitter streams. I’ve decided to enter the competition and visualize the stream of tweets in a fun and engaging way. As the competition closed on 11th July, my entry was selected as one of the winners!
The Entry
My entry, Tweet For Your Team shows the tweets of the two teams simultaneously. It measures the live intensity of the tweets (how many are written per minute for each team) and also analyzes their mood by matching keywords and using simple rules to decide whether a tweet carries positive or negative emotions for the team.
The entry also allows visitors to get involved and cheer for or against their team with a single click sending a shout visible to other users off the application. See this post on all the details on the application functionality.
Winners of the competition were announced just before the World Cup 2010 final and I was happy to see my entry being selected one of the two winners. As the judging panel wrote in their summary: “Gergely created a really engaging application that you could easily sit and watch and interact with during any live World Cup match.”
Why Silverlight?
I’ve used Silverlight to implement the application on top of the live streams. Silverlight turned out to be a great choice for implementing this application for several reasons.
Development time
It took a total of a few days to develop the application, however I was able to finish a working prototype of the application rapidly, in less than 8 hours. From there on I’ve spent most of the time working on the visuals and improving the mood determining algorithm.
Silverlight is indeed great for prototyping quickly and thanks to it’s separated view and code behind concern, it’s quite easy to radically modify the looks of an application down the line.
Performance
During games, the application had quite high load: up to 3500 tweets per minute were coming in per team. This meant up to 10 updates per second on the application interface which Silverlight dealt with surprisingly well after a few tweaks.
Media and Effects
Adding media and visual effects to the application is really easy and quick with Silverlight. I’ve decided late down the road to add some sound effects whenever someone was cheering and vuvuzela background music – all done in a few lines. Also, stunning visual effects can be achieved by using animations and playing with the opacity of elements. I was able to spice the feel of my application up in a few hours of time.
Summary
Silverlight turned out to be an efficient way of creating a visually appealing and performant World Cup mashup in a short period of time. World Cup 2010 is over, so the application isn’t as intense as it was during the games, but I’d still encourage you to take a look at it or watch the video recorded during one of the World Cup games.
Printing support has been introduced in Silverlight 4. This means that any part of the visual tree can be printed in a simple way via API calls. This article gives an overview of how to execute basic printing, looks at what happens when printing complex objects (e.g. charts) and describes how to auto scale elements to fit the printed page.
Printing Basics
The API calls to make printing happen in Silverlight couldn’t really be much easier. To print, one has to create a PrintDocument class (found in the System.Windows.Printing) class. After this object created, one has to subscribe to the PrintPage event and call the Print method(). In the PrintPage event the visual tree element to be printed has to be passed. So the simplest printing scenario looks like this:
UIElement elementToPrint;// The element to be printed
PrintDocument doc =new PrintDocument();// Create the PrintDocument object that will do the printing
doc.PrintPage+=(s, args)=>{// Set the element that needs to be printed.// As soon as this is set, printing starts
args.PageVisual= elementToPrint;}
Printing events
Three events are available when printing, all of which are events of the PrintDocument object. These are:
BeginPrint: this event fires right when the printing has started, after the user has been prompted the print dialogue and selected the printer to use. So this event does not fire before the printing is started, but rather at the exact beginning of it
PrintPage: fired before each page is printed. In this event one can specify the exact contents of the next page to be printed
EndPrint: fired when printing has ended or the user has cancelled the printing.
It’s important to note that the PrintPage event is fired for every printed page and it’s the developers responsibility to specify the contents of the next printed page, Silverlight doesn’t do this task. It’s safe to say therefore that the current printing API is quite low level: this means lots of freedom for specifying the printed content, but also implies extra development needed for extra features like multi page printing and pagination.
Printing a chart
There are a couple examples on various blogs that demonstrate printing simple elements like labels and grids. However to test the functionality of the printing API I decided to see what happens when printing charts.
To test this I’ve constructed charts with the help of the Silverlight Toolkit. So I’ve created four different charts and tested them being printed by adding printing support similar to as described above (the source code is available at the end of the post). I’ve also implemented printing the whole page itself (the only difference in printing a single chart or the whole page is which element the PageVisual is pointing at). Try the example for yourself:
The other day I wanted to find out what version of Silverlight is installed on my computer. This task is actually not as simple as it sounds as the Silverlight plugin is actually browser dependent: there’s a different one installed for Internet Explorer and a different for other browsers. The only way I’ve found to determine current Silverlight version is through Javascript.
Silverlight version detection: Internet Explorer
For Internet Explorer the ActiveXObject(“AgControl.AgControl”) has to be created. This object has and isVersionSupported(versionNumber) method which returns whether versionNumber is supported.
var AgControl =new ActiveXObject("AgControl.AgControl");var version ="3.0.50106.0";// The Silverlight version to test forif(AgControl ==null)alert("Silverlight is not installed!");elseif AgControl.isVersionSupported(version)alert("Silverlight v"+ version +" is supported.");elsealert("Silverlight v"+ version +" is not supported!");
Unfortunately it does not have a method that would return the current version thus to obtain the current version, version numbers have to be iterated. In my version detection script I’ve simply implemented a binary search that loops through the parts of the version numbers (major, minor, build and revision versions) determining the greatest version that is still supported. Not a very nice solution but the AgControl object leaves no other choice!
Silverlight version detection: other browsers (Firefox, Google Chrome, Safari etc)
For other browsers getting the Silverlight version is quite simple. The navigator.plugins["Silverlight Plug-In"] object contains information on the Silverlight plugin. It has the description member variable which contains the Silverlight version. This class makes version detection really simple compared to the hassle one has to go through with Internet Explorer!
var nav = navigator.plugins["Silverlight Plug-In"];if(nav ==null)alert("Silverlight is not installed!");elsealert("Silverlight version "+ nav.description+" is installed.");
Silverlight version detection script
I have created a function that returns the current Silverlight version or -1 if Silverlight is not installed. This script is just a mixture of the Internet Explorer version detection part (with the binary version search implemented) and the other browsers detection script.
See this version detection script in action:
You can use the script the following way:
var slVersion = GetSilverlightVersion();if(slVersion !=-1)
document.writeln("Your Silverlight version is: <strong>"+slVersion +"</strong>");else
document.writeln("<strong>Your do not have Silverlight installed on this computer</strong>");
You can download the Javascript file here: SilverlightVersion.js, or download a standalone HTML version (where the script is embedded within the HTML) here: SilverlightVersion.html.
You can also simply copy the script source code from here:
Silverlight gives the developer the possibility of completely customizing the developed application in all aspects. Defining fonts used for displaying text is no exception. However there are multiple ways on how to go ahead with specifying fonts to use, this article attempts to summarize the options.
Using built-in fonts
Silverlight comes with some fonts that can be used by default, often referred to as built-in fonts. This naming is not entirely correct as the Silverlight runtime does not contain any fonts. However if the specified font is present on the machine, it can be used by Silverlight. The list of these fonts can be found here.
Even though the list contains about 40 fonts, the selection is different on clients running Windows and those running OS X. The “web safe” list – the fonts that are generally installed on both Windows and OS X – are the following subset: Arial, Arial Black, Comic Sans MS, Courier New, Georgia, Lucia Grande, Lucia Sans Unicode, Times New Roman, Trebuchet and MS Verdana.
To specify a font of the default font types, simply specify the FontFamily property of the visual element:
Hello, World!
(Note that if the specified font can not be found on the client, Silverlight will fall back to the basic font type.)
Application displaying all of the built-in fonts available in Silverlight
To visualize the fonts available in Silverlight I’ve created a small application that lets one play around with the default fonts: