Nooks and Crannies of Expression Blend: Artboard Objects List

I can’t even find this one in the Keyboard Shortcut list provided in the User Guide of Expression Blend, so I made up a name for it: The Artboard Objects List:

ArtboardObject List

Known from several drawing programs, this list shows the objects under the mouse cursor when you hold Ctrl and Click the Right Mouse Button. It highlights the currently selected object and lists all other objects overlapping each other from the topmost at the top of the list to the one at the bottom on the bottom of the list. Notice that the order of this list is opposite to the default order in de Objects and Timeline Panel (when you have not changed the order of the panel using the Sort by Z-order option at the bottom left of that panel). Actually, this order is logical for what it shows: the stack of objects in the Artboard under your mouse cursor.

Notice also the option to Pin or UnPin the Active Container. This makes is easier to insert newly created objects in a container like the RegularPolygon Shape in the Grid here inside the RadioButton…


Typography in Silverlight 5

Silverlight 5 is released and contains the Typography features that already existed in WPF. Designers can use these features to make beautiful typographic designs.

SilverlightTypographyThanks to the qualities of the OpenType font format, several typographic features are now available to every web designer. Combining TrueType and Postscript outlines in one format, smaller file sizes, more typographic control and allowing far more characters in a single font file have resulted in a much more versatile use of fonts. The Typography object is available to you inside a TextBlock or TextBox tag. Attributes of this object lead to various typographic results.

Inside a TextBlock or TextBox, a Run element is used that can only contain unformatted text. Properties of the Typography object are applied through this Run element. To group some of the Run elements together, use a <Span>. Both Run and Span have no inherent rendering.

One concept associated with typography is Kerning . Kerning is embedded in the selected font file and Silverlight has no influence on it other than being able to use it or not. You can set the Typography.Kerning attribute to False. The default setting is True.

Superscript and Subscript are Variants of normal characters in a font, placed on respectively a higher or lower baseline than the rest of the text. Other Variants are Normal, Titling, Inferior, Ordinal and Ruby. Note that a Superscript and a Subscript Variant needs to be present in the font file you use.

Nobody should use a smaller font size of normal Capitals when you really need SmallCaps. Spacing of SmallCaps is different and weight and proportion of the letters are adapted to their size and use. Also, for titling purposes capitals with elegant, slender stems are possible, if they are accounted for in the specified font. Setting the property Typography.CapitalSpacing=”True” is a good idea for titles or text that are in capitals, for the spacing between capitals and lowercase letters differs from the spacing between all capitals.

Ligatures are Alternates for two characters that would collide when spaced normally. In the lowercase combination of f and i for example, the point of character i interferes with the end of the stroke of the f regularly. So in the ligature this issue is solved. The same is true for ff, fl, ffi, ffl and many other character combinations. In OpenType fonts standard ligatures are enabled by default in Silverlight 5. If for some reason standard ligatures should be disabled, use the property Typography.StandardLigatures=”False”. Other reasons for ligatures are esthetic, resulting in discretionary or historic ligatures, using Typography. DiscretionaryLigatures and Typograpy.HistoricalLigatures. Ligatures must be present in the font file for you to make them visible with the Typography object.

Swashes are decorative elements of characters associated with calligraphy. Extended serifs and strokes on existing characters may be part of your OpenFont file. To enable a Swash on a character set Typography.StandardSwashes=”1”. When a standards Swash doesn’t result in an agreeable result setting Typography.ContextualSwashes=”1 for that character is also an option.

OpenType has so many positions for characters available, that Stylistic Alternative characters are at your disposal. To enable an alternative character, set the Typograhy.StylisticAlternates property. Random use of alternatives is possible when you specify Typography.ContextualAlternates=”True”, a great way to help a script font in suggesting true handwriting. A font may also contain AnnotationAlternates. These are Glyphs in circles, squares, parentheses, diamonds or rounded boxes used for annotation of images of illustrations. In code-behind this index can be set with Typography.AnnotationAlternates.

Some characters in a font may be designed to be used together, because they look better next to each other or work together somehow. These characters are combined in a stylistic set and a maximum of 20 of these sets may be set in code-behind.

Numerical features of OpenType include Typography.Fraction=”Slashed” or Typography.Fraction=”Stacked”, old style numerals with Typography.NumeralStyle=”OldStyle” inside a Run tag and Tabular or Proportional alignment with Typography.NumeralAlignment=”Tabular” and even, where available, a slashed zero using Typography.SlashedZero=”True”.

Here’s the XAML I used for the image at the beginning:

<StackPanel Background="White" Margin="0,0,0,0">
<TextBlock FontFamily="Adobe Caslon Pro" FontWeight="Normal" TextAlignment="Center" FontSize="200" Typography.StandardLigatures="True">
<Run FontStyle="Italic" Typography.StylisticAlternates="1">fi</Run>
<Run Foreground="Red" FontStyle="Italic" Typography.StylisticAlternates="1">fl</Run>
<Run FontStyle="Italic" Typography.StylisticAlternates="1">ff</Run>
<TextBlock FontFamily="Adobe Caslon Pro" FontWeight="Normal" Margin="0,-150,0,0" TextAlignment="Center" FontSize="200" Typography.StandardLigatures="True">
<Run FontWeight="Normal" Typography.StylisticAlternates="1">fi</Run>
<Run FontWeight="Normal" Typography.StylisticAlternates="1">fl</Run>
<Run FontWeight="Normal" Typography.StylisticAlternates="1">ff</Run>
<TextBlock FontFamily="Adobe Caslon Pro" FontSize="24" Margin="0,-125,0,0" TextAlignment="Center">
<Run Text="Superscript: M"/><Run Foreground="Red" Text="2" Typography.Variants="Superscript"/>
<Run Text="Subscript: H"/><Run Foreground="Red" Text="2" Typography.Variants="Subscript"/><Run Text="O"/>
<Run FontStyle="Italic" Text="Fraction: 8"/><Run Foreground="Red" FontStyle="Italic" Text="1/2" Typography.Fraction="Slashed"/><LineBreak/>
<Run Text="CAPITALS" Typography.Kerning="True"/>
<Run Text="SmallCaps" Foreground="Red" Typography.Capitals="SmallCaps"/>
<Run Text="AllSmallCaps" Typography.Capitals="AllSmallCaps"/><LineBreak/>

Also check out Silverlight 5 OpenType Support from Pete Brown at 10REM.NET.


Silverlight wallpaper 1920×1080 HD

Since I got a new computer screen at work my old Silverlight wallpaper at a 1280 x 1024 resolution didn’t fit any more. I could not find one for a 1920×1080 resolution, so I had to create my own. Luckily I happen to have a hires Silverlight logo available and know a little about Photoshop filters… Like it or not, here it is:

SilverlightWallpaper 1920x1080

Click image to download in 1920×1080


A Style for the Silverlight CoverFlow Control Slider

I’ve been working with the Silverlight CoverFlow Control lately and think the default Silverlight Slider at the bottom of the screen sticks out like a sore thumb:
So, I’ve create a new Style for the Slider, resembling the original Cover Flow slider.
This is a Style for a Silverlight slider control, meant to be used on a black or dark background. It has rounded sides for the Track as well as the Thumb. The Track looks like it is lower because of the inner shadow at the top. The Thumb also has a shadow, but its surface is flat. This is only the Horizontal Template, so nothing will show when it is used vertically.
The Project File is on my SkyDrive, but the Style is simple enough to reproduce it here…
De XAML is a regular Slider with a Style:
<Slider Style="{StaticResource CoverFlowSliderControl}" Maximum="100" LargeChange="10" SmallChange="1" Value="50"/>
The Track has its own style, used in the ControlTemplate later on:
<Style x:Key="CoverFlowSliderTrackStyle" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="12" />
 <Setter Property="RadiusX" Value="12" />
 <Setter Property="StrokeThickness" Value="2"/>
 <Setter Property="Stroke">
 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
 <GradientStop Color="#FF202020" Offset="0"/>
 <GradientStop Color="#FF404040" Offset="1"/>
 <Setter Property="Fill">
 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
 <GradientStop Color="Black" Offset="0"/>
 <GradientStop Color="#FF202020" Offset="0.4"/>
The Thumb is no more than two rectangles, but both have their own Style:
<Style x:Key="CoverFlowSliderThumb" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="10" />
 <Setter Property="RadiusX" Value="10" />
 <Setter Property="StrokeThickness" Value="2" />
 <Setter Property="Stroke" Value="#FF4B4B4B"/>
 <Setter Property="Fill">
 <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.43,-0.02">
 <GradientStop Color="#FF252525" Offset="1"/>
 <GradientStop Color="#FF787878" Offset="0"/>
 <GradientStop Color="#FF424242" Offset="0.622"/>
 <Style x:Key="CoverFlowSliderThumbCover" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="8" />
 <Setter Property="RadiusX" Value="8" />
 <Setter Property="StrokeThickness" Value="0" />
 <Setter Property="Fill" Value="#FF404040" />
 <Setter Property="Margin" Value="3" />
 <Style x:Key="ThumbStyle" TargetType="Thumb">
 <Setter Property="Margin" Value="0,2" />
 <Setter Property="Width" Value="50" />
 <Setter Property="Template">
 <ControlTemplate TargetType="Thumb">
 <Grid Margin="2,0">
 <Rectangle x:Name="Thumb" Style="{StaticResource CoverFlowSliderThumb}"/>
 <Rectangle x:Name="ThumbCover" Style="{StaticResource CoverFlowSliderThumbCover}"/>
 <Setter Property="Effect">
 <DropShadowEffect Direction="360" Opacity="0.5" ShadowDepth="3"/>
There are two Repeatbuttons to the left and to the right of the Thumb. They are invisible and use the same Style:
<Style x:Key="RepeatButtonStyle" TargetType="RepeatButton">
 <Setter Property="Template">
 <ControlTemplate TargetType="RepeatButton">
 <Rectangle RadiusY="6" RadiusX="6" StrokeThickness="2" Fill="Transparent"/>
Finally, here is the Style for the Slider Control with the ControlTemplate that uses all Styles above…
<Style x:Key="CoverFlowSliderControl" TargetType="Slider">
 <Setter Property="Height" Value="24" />
 <Setter Property="Template">
 <ControlTemplate TargetType="Slider">
 <Grid x:Name="HorizontalTemplate">
 <ColumnDefinition Width="Auto"/>
 <Rectangle x:Name="Track" Grid.ColumnSpan="3" Style="{StaticResource CoverFlowSliderTrackStyle}"/>
 <RepeatButton x:Name="HorizontalTrackLargeChangeDecreaseRepeatButton" Grid.Column="0" Style="{StaticResource RepeatButtonStyle}"/>
 <Thumb x:Name="HorizontalThumb" Grid.Column="1" Style="{StaticResource ThumbStyle}"/>
 <RepeatButton x:Name="HorizontalTrackLargeChangeIncreaseRepeatButton" Grid.Column="2" Style="{StaticResource RepeatButtonStyle}"/>
The result is a Cover Flow Slider that nicely fits in with the rest of the Cover Flow Control:
Check out the Comments below about why this picture is up here…
Slide the Slider
Download the source for this Slider

Nieuw leven voor Silverlight: Silverlight 5 beta in april

De beta van Silverlight 5 wordt in de lente verwacht, waarschijnlijk tijdens de MIX 2011 conferentie op 12 tot en met 14 april in Las Vegas. De definitieve versie van Silverlight 5 wordt daarop in de loop van 2011 uitgebracht.

Ook bij de komende versie van Silverlight is gekeken naar de features die het meest gevraagd zijn op Daar staan Full Databinding support en 3D bovenaan in de lijst. Verschillende aangekondigde features vindt je terug in de bovenste regionen, maar ook andere handige features worden onderdeel van Silverlight 5. Nadruk ligt op verbetering en uitbreiding van de bestaande functionaliteit, maar er zijn een paar uitzonderingen: ondersteuning voor 3D bijvoorbeeld.

3D en graphics

De grootste verassing in de Keynote van Scott Guthrie op de Silverlight Firestarter Web Cast was voor mij de aankondiging van 3D voor Silverlight. In de keynote video is vanaf 50:50 tot 55:50 een indrukwekkende demo te zien van wat er mogelijk wordt met 3D in Silverlight. Of 3D op dezelfde manier gaat werken als in Windows Presentation Foundation, valt nog te bezien. Er zijn in ieder geval modellen, animated cameras, textures en bumpmapping in de Silverlight implementatie aanwezig. De performance van de demo is in indrukwekkend. Grafische verbeteringen als een 3D immediate Mode Graphics API, GPU accelerated 3D zullen daaraan bijgedragen hebben. Daarnaast zijn Fluid Layout Transitions in Silverlight 5 beschikbaar, die het animeren van onderdelen van de UI nog eenvoudiger maken.

Tekst en printen

Daarnaast krijgt Silverlight 5 serieuze typografische verbeteringen. De scherpte van de tekst wordt verbeterd, het wordt mogelijk om tekst over meerdere kolommen te laten lopen. Er wordt volledige OpenType support beloofd, waaronder de toepassing van Leading en Kerning van characters in lettertypes. Het printen van tekst in Postscript vector format maakt niet alleen haarscherpe prints mogelijk, maar zal ook meer controle bieden over wat er precies geprint wordt en niet alleen wat er in de visual tree aanwezig is.

Data en binding

Een ander opmerkelijke en nuttige feature in Silverlight 5 wordt het zetten van breakpoints in de XAML. Dit werkt hetzelfde als breakpoints in code, maar zal daadwerkelijk een XAML-bestand openen en stoppen op de regel met het breakpoint. Van daaruit is het debuggen van data binding voorhanden. In de Locals Window worden fouten in de binding en in de final source de properties met de huidige waarden daarvan zichtbaar. Dat maakt het oplossen van problemen met bindings een stuk eenvoudiger. Bindings on Style setters maken het veranderen van application resources beschikbaar, zodat het onmiddelijk veranderen van Themes eindelijk wel  kan. Voor RIA services kan data opgeslagen worden in de cloud. Custom markup extentions helpen om een MVVM patroon beter te implementeren. Implicit Data Templates zorgt voor een default uiterlijk van een bepaald datatype over de hele applicatie heen. Relative Source binding maakt WPF features voor databinding eindelijk beschikbaar in Silverlight.


Hardware media decodering geeft betere video-ervaring, terwijl CPU en batterij worden ontzien. Power Management zal bij dat laatste zelfs nog meer helpen. Pitch correction voor audio en video heet in Silverlight 5 TrickPlay. Silverlight krijgt ook de functionaliteit om afstandbedieningen aan te sturen, zodat een zogenoemde “Ten feet experience” beter ondersteund kan worden vanuit een Silverlight applicatie. Ik hoop nog altijd dat MediaCenter Markup Language (MCML) wordt vervangen door XAML, maar dat is wellicht een brug te ver.  IIS Media Services 4.0 maakt smooth streaming naar WP7, maar ook de iPhone en de iPad mogelijk met betere performance en meer mogelijkheden. Het wordt bijvoorbeeld mogelijk om Azure te gebruiken voor IIS Media Services.

Silverlight 5 zal weer talloze verbeteringen hebben ten opzichte van de huidige versie. Zo komt er een 64-bit Silverlight Runtime die sneller start, beter presteert en meer mogelijkheden biedt. Een Coded UI recorder brengt testen van de userinterface binnen bereik. Out-of-Browser Silverlight applicaties kunnen meerdere subwindows hebben, die zelfs snappen naar de kanten van het scherm in Windows 7. Entreprise Policy support laat trusted applications binnen die vertrouwde omgeving uit de sandbox komen. P/invoke laat je unmanaged DLLs en Win32 APIs aanspreken voor betere integratie met het OS en met apparaten.

Als wilt kan je alles nog eens nalezen op de Future of Microsoft Silverlight site.

When dynamically creating objects in code, use Styles

When you need to create objects in code, you can actually build up the entire look and feel in code.

This results in large blocks of code that do nothing special, but set the visual properties of an object:

Grid grdNow = new Grid();


//create Circle

Ellipse cirNow = new Ellipse();

cirNow.Height = 25;

cirNow.Width = 25;

cirNow.VerticalAlignment = VerticalAlignment .Center;

cirNow.HorizontalAlignment = HorizontalAlignment.Center;

cirNow.Fill = new SolidColorBrush (Colors.Red);

cirNow.Margin =new Thickness(5,5,5,5);


//create TextBlock

TextBlock txtNow = new TextBlock();

txtNow.VerticalAlignment = VerticalAlignment.Center;

txtNow.HorizontalAlignment = HorizontalAlignment.Center;

txtNow.Foreground = new SolidColorBrush(Colors.White);

txtNow.FontWeight = FontWeights.Bold;

txtNow.FontSize = 14;

txtNow.Margin =new Thickness(0,0,0,2);

txtNow.TextWrapping = TextWrapping.NoWrap;



//add objects to grid




The drawback of this is that it is a lot of code and hard to maintain. The looks are integrated in the code and that is not what you want.

In Silverlight and WPF there is a standard model to separate the code from the look and feel of the application you’re building. It’s called XAML.

XAML is a markup language that’s easily generated by code and easily maintained by non-programmers with tools of even by hand.

When you are creating objects on the fly you should use Styles. These determine the way the object looks. Only keep the properties necessary for dynamically placing your object on the screen in your code:

Grid grdNow = new Grid();
Ellipse cirNow = new Ellipse();
TextBlock txtNow = new TextBlock();

cirNow.Style = App.Current.Resources["NowStyle"] as Style;
txtNow.Style = App.Current.Resources["NowTextStyle"] as Style;


This is a lot less code. Below is the markup that you shouldn’t have to worry about when you use Styles in your C# code.

You can even just create an empty Style block in App.xaml: <Style x:Key=”NowStyle” TargetType=”Ellipse” /> and thus use it with default values.

The look of these dynamically created objects can be changed later on or even be themed using a separate ResourceDictionary. A designer can come in at any time and change these properties using a Tool like Expression Blend.

<Style x:Key="NowStyle" TargetType="Ellipse">
    <Setter Property="Height" Value="25"/>
    <Setter Property="Width" Value="25"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="Fill" Value="Red"/>
    <Setter Property="Margin" Value="5"/>
<Style x:Key="NowTextStyle" TargetType="TextBlock">
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Margin" Value="0,0,0,2"/>
    <Setter Property="TextWrapping" Value="NoWrap"/>
    <Setter Property="Text" Value="nu"/>

So, when you find yourself creating a lot of C# code to set the visual properties of a dynamically created objects: Stop!

Create a Style in XAML and refer to that Style instead.


DEMO: 5 gotchas combining SketchFlow, Visual Design and Silverlight Banners

Recently we created a demo. It was in SketchFlow, but it was not really a sketchy demo. Some screens are in the typical SketchFlow look, but for three important scenarios we’ve created a Visual Design. For the Homepage and a Product page in the demo we even created a Silverlight Banner, including the navigation inside the banner.

We’ve actually presented it inside the SketchFlow Player with panels collapsed. We gained the ease with which to connect the screens, in combination with the Behaviors the make parts of the demo interactive. And we combined real Silverlight applications inside the SketchFlow demo and they worked just fine. This is a demo that is meant to impress a customer.

I’ve collected some some gothas we run into when creating this demo:

  1. Large images are not include as a Resource, but as Content. In the Blend Options screen you’ll find a slider setting the limit for large images. You’ll get a warning when you import an image larger than that limit. You can choose to include the image as Content, not as Resource. This will result in the image not showing in your SketchFlow Player. So be sure to include all images in a subfolder in the MyProject_Screens folder and make sure the path in the Image Source is correct. When images show up in the root of a deployed SketchFlow project, you’re in trouble…
  2. When you use a Silverlight application inside a SketchFlow Page, you can use the NavigateToScreenAction inside your UserControl, but screens will not show up in the list in the Properties Panel. It has no use to create a reference to the SketchFlow project. You can add the correct path manually. You can find the names of the Screens in the Projects Tab.
    <i:EventTrigger EventName="MouseLeftButtonDown">
        <pi:NavigateToScreenAction TargetScreen="MyProject_DemoScreens.Screen_1"/>
  3. You can use Components as Masterpages. Remove all elements in the Visual Design that change between pages and put the rest in a Component screen. This allows you use this UserControl as the first element of a page. You can create separate boxes with content on the page to link to different pages in the prototype.
  4. Alternatively, use HyperlinkButtons with NavigateToScreenActions Behaviors to create “HotSpots” on a background image if you want to navigate to different screens. You’ll have to edit the HyperlinkButton ControlTemplate to remove the FocusVisual that appears when you click the control. Then they are invisible, but still catch the Click Event for the NavigateToScreenAction. It will navigate to the screen you enter as a Target.
  5. Use SketchFlowAnimation or GoToStateAction Behaviors for interactive elements on the page. This way you can use highlights and let pop-ups appear and disappear. SketchFlow Behaviors rock!


Using Silverlight 4 StringFormat for Data Binding a TextBlock to a Slider with no decimals showing

In Silverlight 4 it is possible to use the StringFormat extention to format output from Data Binding. I was always looking for a way to remove the trailing decimals from a TextBlock that was bound to a Slider. Today I found the answer:

<TextBlock x:Name="txtWeight" Text="{Binding Value, ElementName=sldWeight, StringFormat=\{0:n0\}}"/>

This says: Use the result as a number with zero decimals.

Use StringFormat=\{0:n1\}} if you want one decimal and StringFormat=\{0:n2\}} for two decimals. You can also use StringFormat=p for Percentage, StringFormat=c for Currency…

The Designer Silverlight site has more details…


Create a Button Control from an Expression Design drawing

I’ve placed a PushButton Design file in the Expression Gallery. A thousand people have actually downloaded the .design file. Only one question rose, asking how to implement that drawing as a Button Control. Here are the steps to do that:


In Design:
– Click the square on the Layer named PushButton to select all elements
– Select File/Export and in the dialog choose XAML Silverlight 4 Canvas, Leave Text Editable, set Live Effects to Convert to XAML,  call it PushButtonNormal.xaml, remember where it is located after export. Click Export All.
– Click the square on the second Layer named PushButton Pressed to select all elements
-Select File/Export and use the same settings and location. Name it PushButtonPressed.xaml. Click Export All.

In Blend:

– Start a new Blend Silverlight Application, Call it PushButtonControl
– Open MainPage.xaml in the Code Editor using View/Active Document View/XAML View.
– Create a closing the tag for the Grid Named LayoutRoot.
– Open the PushButtonNormal.xaml file in Notepad. Cut the inner Canvas named PushButton, Paste in inside the LayoutRoot Canvas and remove Width, Height and Canvas.Left and Canvas.Top.
– Open the PushButtonPressed.xaml file in Notepad. Cut the inner Canvas named PushButton_Pressed, Paste it under the PushButton Canvas and remove Width, Height and Canvas.Left and Canvas.Top.
– Resolve naming conflicts for Ellipses, you can only have objects with unique names.
– Switch to Design Vieww using View/Active Document View/Design View.
– Right Click the PushButton Layer in the Objects and Timeline Panel. Select Group into…/Grid from the context menu.
– Right Click the PushButton layer in the Objects and Timeline Panel. Select Make into Control… from the context menu.
– In the dialog select the Button control and name it PushButtonControl. Click OK.
– This will create a Button Control and open ControlTemplate Editing Mode. A ContentPresenter is added to the Button. Because the PushButton container is a Canvas you have to reposition this using the Left and Top properties.
– Click the [Button] button in de Breadcrumbs at the top left of the Artboard to go out of Template Editing Mode.
– Right Click the PushButton_Pressed layer in the Objects and Timeline Panel. Select Cut from the context menu.
– Left Click the [Grid] layer in the Objects and Timeline Panel. Select the [Grid] button in de Breadcrumbs at the top left of the Artboard to go into Template Editing Mode again.
– Right Click the [Grid] layer and select Paste from the context menu. This will place the Pressed state of the button over the Normal state. Remove the top most Ellipse. This is the transparent shadow and should not show twice. Drag the PushButton_Pressed layer up so it is above the [ContentPresenter] layer. The word Button should appear.
– Set the Opacity Property of PushButton_Pressed to Zero (0%).
– Now you should have a [Grid] with 3 layer in it: PushButton, PushButton_Pressed and [ContentPresenter]. The Normal state should be visible. The word Button should be visible in it.
– Open the States Panel (Window/States should have a check before it) and select the Pressed State. The Pressed state recording should go on, showing a red frame around the Artboard.
– Set the Opacity of PushButton_Pressed back to 100%.
– Click the Base layer at the top of the States Panel and switch between the Pressed and Base state. Make sure the Buttons overlap exactly.
– Click the [Button] button in de Breadcrumbs at the top left of the Artboard to go out of Template Editing Mode.
– Select File/Save all
– Press F5 to build the project, so you can test it.

Optimization would include replacing the Canvases with Grid containers while keeping all Ellipses in their places. This would allow for better control of button size and placement of the ContentPresenter.


Easy as Pie: Percentage Pie-Charts with the Expression Blend 4 Pie Shape

During the evolution of Silverlight and Expression Blend we’ve had to create Pie Charts for various projects. Often these were to illustrate the state of a percentage value in the application. Thus we’ve build our own a few times over. Now, with the new Pie Shape in Expression Blends 4 this has become a no-brainer. Here´s how:

 PieShape01  PieShape02 

  1. Create a new Silverlight Application project in Blend 4
  2. Open the Asset Panel and select the Shapes category
  3. Select the Pie Shape
  4. DoubleClick the Pie Shape at the bottom of the ToolBox so it is added to the Artboard with default values of StartAngle 90 and EndAngle 360
  5. Name it Pie1 in the Objects and Timeline panel. This way you can use code to access its properties.
  6. If you want you can give it a Fill Color to see it better.
  7. Add an event handler called UpdateArcEndAngle on the MouseLeftButtonUp event of the LayoutRoot Grid.
  8. In the Code Behind file (MainPage.xaml.cs) add a line of code to update the StartAngle of the Arc:private void UpdateArcStartAngle(object sender, MouseButtonEventArgs e)
        Pie1.StartAngle += 45;
  9. Build the project and click the Pie to update it with 45 degrees each time you click it. When the Pie has reached the 360 degrees, it with start again at 45.

Of course, you can style a Pie Shape any way you want. Now it is easier than ever to show a percentage Pie Chart…

 Pie01  Pie02



Focus on FocusVisualElement in Silverlight buttons

The FocusVisualElement is the equivalent of the dotted line that you see in Windows interfaces and on browser pages around an object on the page that “has the focus”. This means that it will receive the input a user is giving with a mouse, keyboard or touch. Actually, web designers don’t really like these dotted lines, because they degrade the look of their interface. It may disturb the carefully crafted look and feel of the page. But this FocusVisualElement has a function.

Normally I’m not so eager to use buttons as controls for showing examples. It usually doesn’t lead to an interesting visual result. As a designer my examples should look more interesting. Fortunately in Silverlight you can create other shaped and colored buttons easily using the Make into Control… option in the contextmenu of graphic elements gathered in a Grid. In this case the I’d like to focus on the FocusVisualElement element, so Buttons are my first choice.

In Silverlight the FocusVisualElement is an actual graphical element that is part of a control’s ControlTemplate. In Blend you can access this template by selecting Edit Template/Edit Current (I’d really like a keyboard shortcut here, but there isn’t, yet).

In template editing mode you can find the FocusVisualElement in every Silverlight control. It’s shape depends on the type of control, but in a Button it is a light blue Rectangle. By default this Rectangle has its Opacity set to Zero and the Focused State makes it visible. This leads to the notion that you can change the looks of this Focused State to anything you’d like:



ButtonFocused2  ButtonFocused

In these images I show how a HyperlinkButton could get a Glow Effect when it is focused. But there’s no reason to leave it at that. The oval Button plays an animation when it is focused. Apart from the Opacity, a TranslationX, Scale and a PointAnimation is applied to a semitransparent Ellipse when the Focused State is triggered. This makes the Ellipse move van left to right. The animation is AutoReversed and repeated Forever.

You can use the VisualStateManager to create the animations. You can also show the TimeLine and create an Storyboard that you paste in de <VisualState x:Name="Focused" /> Visual State. When you create a Button using Make into Control… you can copy the Visual States out of the ControlTemplate of a normal Button and use them in your own.

Make sure your animation for the Focused State of controls are low-key. You don’t want to irritate your users with flashing graphics only because a control is focused!

Working code from these Buttons is on my SkyDrive


Overlapping TabItems with the Silverlight Toolkit TabControl


Standard TabItems are not overlapping, but designers like them to. You may encounter a design with overlapping tabs that you have to create and implement. This is not a simple task, certainly when the tabs have a tapered side that overlaps the tab to the right of it. The Z-Index of these tabs are opposite to the standard layout.

Control Vendors have custom versions of a TabControl, that use properties for overlap. The Toolkit TabControl currently doesn’t support overlapping tabs, but by updating templates and a bit of C# code you can get the same effect. Here’s how it’s done:

Creating an overlapping tab in Expression Design:


  1. Start Design, start a new file with a size of 640 x 480 pixels.
  2. Add a rectangle, 50 pixels wide, 25 pixels high and make its CornerRadius 3 pixels. Make sure the Rectangle is selected.
  3. Choose Object. Convert Object to Path. This way you can change the vertices of the shape.
  4. Select the Direct Selection tool (second from the top in the Toolbox) and select the bottom right two vertices by dragging a selection area around them.
  5. Drag the two vertices to the right, about half the width of the rectangle. Hold the Shift key to constrain the translation horizontally.
  6. Zoom in to the right hand side of the shape. With the Pen Tool selected, at the right bottom corner delete the second vertice from the bottom by clicking on it.
  7. Hold the Alt Key and click the other vertice to make it a rounded point (fig. 1).
  8. Select the Direct Select Tool and move the second vertice from the top to the right. Select the Pen Tool, hold the Alt Key and drag from this anchor point in the direction of the line of the tab, so the sharp corner becomes smooth.
  9. Using the Direct Selection Tool, move the left vertice at the left bottom corner down to the bottom of the tab, delete the other by clicking on it with the Pen Tool selected (fig. 3).


figure 1: Create a round point at the bottom right corner.


figure 2: Create a smooth corner at the top right corner.


figure 3: Remove a anchor point to create a straight corner at the lower left corner.

Double click the Magnifying Glass Icon at the bottom of the toolbox to show the entire drawing. It helps to place the top right corner of the tab at the 0,0 coordinates using the Action Bar at the bottom of the screen. Check if the Foreground color is white and the border is black. Make sure the tab is selected, showing its bounding box and transformation handles, and select Edit, Copy from the menu.

Implementing overlapping tabs in Expression Blend:

  1. Start Blend, Begin a new Silverlight project, Open MainPage.xaml.
  2. Open the Asset Panel, enter Tab in the search box, select TabControl and drag a rectangle on the Artboard. You’ll get a TabControl with two tabs. A reference to System.Windows.Controls.dll is added to the project references and a namespace xmlns:controls is added to your MainPage.xaml file.
  3. The TabControl is a container for the TabItems. It has a four Grids to place tabs on all sides of the tab area. Tabitems are placed in these grids. The TabItems consist of a Header and a Grid as you can see in the Object and Timeline Panel when a tab is selected. Right click a Tab and select Edit Template, Edit a Copy… from the context menu, choose a name and a location for the ControlTemplate and click OK.


figure 4. Creating a TabItem ControlTemplate

  1. You’ll enter Template Editing Mode for the TabItem. The Objects and Timeline panel shows eight grids and a FocusVisualElement Border. For each of the four sides (Top, Bottom, Left, Right) you’ll see a Selected and a Unselected Part. Control Parts are recognizable by the green icon next to their name. You can also find them in the Parts Panel.
  2. Locate the TemplateTopSelected Grid in the Object and Timeline Panel and open all the borders and grids that are part of it by clicking the small triangles in from of it. Drag the ContentControl named HeaderTopSelected up to the TemplateTopSelected Grid so it moves to the same hierarchical level. Now you can delete the rest of the content of the TemplateTopSelected Grid. Also delete all the animations that reference those shapes if they are not deleted by Blend.
  3. With this Grid selected, choose Paste from the edit menu. This will place the tab you created in Expression Design into the grid. Remove its Margins to make the tab fit inside the Grid.
  4. Drag the layer of the new Path up so it is placed right beneath the TemplateTopSelected Grid and above the Focus and Disabled visuals in the Objects and Timeline Panel. Move the HeaderTopSelected Content Control beneath the Path.
  5. Repeat Step 3 and 4 for the TemplateTopUnselected Grid. Make its Foreground a slightly darker color than the selected state of the tab.
  6. Set for both the TemplateTopSelected as the TemplateTopUnselected Grid the left margin to –20 pixels. This will ruin the bounding box placing in Blend, but move the tabs to the left at runtime.
  7. Make sure the Grid for the selected state of the tab has a Path at the bottom, that makes the connection with the tab area beneath it. It is important that a tab connects to the area that shows when a tab is selected.
  8. You may want to delete the FocusVisualTop border because it is rectangular and your tabs are not. Also remove any animations targeting this control.
  9. Scope up to the Control Level using the breadcrumbs at the top of the screen or the Return Scope to [UserControl] button at the top of the Objects and Timeline Panel.
  10. Right Click the TabControl and Select Edit Additional Templates, Edit Layout of Items [ItemPanel], Create New. Make sure it is a StackPanel with its Orientation set to Horizontal. Scope up to the Control Level.
  11. Right Click the TabControl (not a tab) and Select Edit Template, Edit a Copy… Give the System_Windows_Controls_Primitives:TabPanel a left margin of 20, but leave the other margins as they are: margin=”20,2,2,-1″ compensating for the negative left margin on the first TabItem.
  12. Use the Visual State Manager to create a state for a MouseOver that is a light gray between the selected and unselected Foreground colors. A transition time of half a second gives the right effect.

        <controls:TabControl x:Name=”TabControl” Width=”500″ Height=”100″
             Style=”{StaticResource TabControlStyle1}”
             ItemsPanel=”{StaticResource ItemsPanelTemplate1}”
            <controls:TabItem x:Name=”Tab_1″ Header=”Tab 1″
                 Style=”{StaticResource TabItemStyle1}”>
                <Grid Background=”#FFE5E5E5″>
                    <TextBlock Text=”Area 1″ Margin=”20″/>
            <controls:TabItem x:Name=”Tab_2″ Header=”Tab 2″ 
                Style=”{StaticResource TabItemStyle1}”> 
                <Grid Background=”#FFE5E5E5″>
                    <TextBlock Text=”Area 2″ Margin=”20″/>
            <controls:TabItem x:Name=”Tab_3″ Header=”Tab 3″
                 Style=”{StaticResource TabItemStyle1}”>
                 <Grid Background=”#FFE5E5E5″>
                      <TextBlock Text=”Area 3″ Margin=”20″/>
            <controls:TabItem x:Name=”Tab_4″ Header=”Tab 4″
                 Style=”{StaticResource TabItemStyle1}”>
                 <Grid Background=”#FFE5E5E5″>
                     <TextBlock Text=”Area 4″ Margin=”20″/>

Getting the ZIndex right

All this will create the right shape and states of the the TabControl, but the order of the tabs is still wrong. By default the first tab is selected and a right tab will overlap a left tab. With overlapping tabs this should be the other way around. Setting the Canvas.ZIndex property of the TabItems in XAML won’t help. The control is initialized with the wrong settings at runtime.

A little C# helps. Thanks to Rachel, who solved this problem in WPF, we can set the overlapping tabs in the right order when the SelectionChanged event of the TabControl is fired:

private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)

    TabControl tabControl = sender as TabControl; 
    tabControl.Dispatcher.BeginInvoke( new Action(() =>
            UpdateZIndex(sender as TabControl)));

private void UpdateZIndex(TabControl tc)

    if (tc != null)
        foreach (TabItem tabItem in tc.Items)
                        (tabItem == tc.SelectedItem ?
                        tc.Items.Count :
                        (tc.Items.Count-1) – tc.Items.IndexOf(tabItem)));

The UpdateZIndex method is invoked in a way that updates all the TabItems. This way a left tab will show above a right tab the way you want in overlapping TabItems.


fig 5. Overlapping tabs have a reversed ZIndex.

Working code is at my SkyDrive

Joe Gershgorin has refactored the code to use a Behavior. This also supp0rts longer text in the headers. You can find his version at:


QuoteFloat: Animating TextBlock PlaneProjections for a spiraling effect in Silverlight


QuoteFloat is an animation for TextBlock elements, inspired by the way the HTC Touch HD shows SMS Text messages. It moves the text up and rotates it at the same time resulting in a spiraling effect. It is done by giving the TextBlock elements a PlaneProjection each and animating the RotationY and GlobalOffsetY properties.

The TextBlock elements are positioned below the bottom of the Canvas. The Canvas has a Clipping Mask so no one will see them until the animation starts. The XAML looks like this:

<Canvas x:Name="cvsBg" Width="500" Height="155"
    Clip="M0.5,0.5 L499.5,0.5 L499.5,154.5 L0.5,154.5 z">
    <TextBlock x:Name="txt1" Text="Txt1" Canvas.Top="192"
        Style="{StaticResource TextBlockStyle1}">
    <TextBlock x:Name="txt2" Text="Txt2" Canvas.Top="228"
        Style="{StaticResource TextBlockStyle1}">
    <TextBlock x:Name="txt3" Text="Txt3" Canvas.Top="265"
        Style="{StaticResource TextBlockStyle2}">

I use two Styles for the two TextBlocks. Notice the second style is BasedOn, so it needs only to define the properties that are different from the first style. The Canvas.Top property is different for all the TextBlocks and defined inline in the XAML above.

<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Width" Value="400"/>
    <Setter Property="Height" Value="25"/>
    <Setter Property="FontSize" Value="21.333"/>
    <Setter Property="FontFamily" Value="Trebuchet MS"/>
    <Setter Property="TextAlignment" Value="Center"/>
    <Setter Property="Canvas.Left" Value="50"/>
<Style x:Key="TextBlockStyle2" TargetType="TextBlock"
    BasedOn="{StaticResource TextBlockStyle1}">
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Canvas.Left" Value="200"/>

The actual animations are quite repetative, being almost the same for all TextBlock elements. The crucial word here is almost: the animations differ for .2 seconds. Stopping the text is the natural result from easing out and the easing in the animation.


<Storyboard x:Name="QuoteFloat" RepeatBehavior="Forever">
        BeginTime="00:00:00" Storyboard.TargetName="txt1"
        <EasingDoubleKeyFrame KeyTime="00:00:00" Value="90"/>
        <EasingDoubleKeyFrame KeyTime="00:00:01.5" Value="0">
                <CubicEase EasingMode="EaseOut"/>
        <EasingDoubleKeyFrame KeyTime="00:00:03" Value="-90">
                <CubicEase EasingMode="EaseIn"/>
… more animations

        <EasingDoubleKeyFrame KeyTime="00:00:00.2" Value="90"/>
        <EasingDoubleKeyFrame KeyTime="00:00:01.7" Value="0">
                <CubicEase EasingMode="EaseOut"/>
        <EasingDoubleKeyFrame KeyTime="00:00:03.2" Value="-90">
                <CubicEase EasingMode="EaseIn"/>
… more animations

The text was not set using code, but in Blend. It then uses a DiscreteObjectKeyFrame for the TextBlock Text property and uses the given String Value.

        <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="Technology requires design"/>
        <DiscreteObjectKeyFrame KeyTime="00:00:03" Value="Imagine users as very intelligent"/>
        <DiscreteObjectKeyFrame KeyTime="00:00:06" Value="No matter how cool you interface is,"/>
        <DiscreteObjectKeyFrame KeyTime="00:00:09" Value="Significant change"/>

The Loaded event of the UserControl is used to start the animation in the MainPage CodeBehind file:

<UserControl x:Class="QuoteFloat.MainPage"
    Width="500" Height="155" Loaded="StartAnim">


private void StartAnim(object sender, System.Windows.RoutedEventArgs e)

Complete Blend project is on my SkyDrive…


Silverlight Togglebutton Push Pin Style with IsoStore

Now you can pin a full-screen app to a second monitor in Silverlight 4, you may want an UI control to facilitate this. In fact, what you need is a ToggleButton. And your ToggleButton has to be communicate it’s function. A Push Pin Style is a good solution for that.

This Push Pin Style for a silverlight (or WPF) ToggleButton is small, totally customizable and free :). It features tooltips to show the action you can do. The setting is stored in IsoStore and picked up the next time you start your app. The states are each represented using a canvas, so you can easily swap the visuals for your own if you want to.


The XAML is simple:

<ToggleButton x:Name="btnPin" Style="{StaticResource btnPin}" Checked="pin" Unchecked="unpin" Content="" ToolTipService.ToolTip="Pin this"/>

Files are too large to include here, but I put the project on my SkyDrive.


Mix Keynote bij Microsoft NL

Ik had het voorrecht om te gast te zijn bij de presentatie van de keynote bij Microsoft Nederland. In combinatie met de SDN had de Silverlight en Expression Insiders usergroup een aantal plaatsen te vergeven. Mensen die zich ingeschreven hebben op hebben een e-mail gehad met een link naar het inschrijvingsformulier voor het evenement. Ze hebben een ochtend de tijd gehad om zich in te schrijven.

Uiteindelijk waren er zo’n dertig mensen vanuit verschillende gebruikersgroepen en invalshoeken naar het nieuwe Microsoft hoofdkwartier gekomen om de aftrap van de MIX 2010 op een groot scherm in een grote vergaderzaal mee te maken. Er waren drankjes en borrelhapjes, maar zodra de videostream op gang was gekomen was iedereen ademloos aan het luisteren en kijken. In sneltreinvaart zijn verschillende mensen en evenzoveel verschillende demo’s aan het oog voorbijgekomen. Enkele opmerkelijke feiten heb ik via Twitter kunnen verspreiden, totdat mijn telefoon het opgaf omdat hij te lang had aangestaan.

De tweets gingen over de 60% marktpenetratie van Silverlight (in Nederland 72%), de mogelijkheid om fullscreen Silverlight video te kijken op een tweede (of derde) scherm, Silverlight als techniek achter Pivot, Blend 4 als gratis update voor Blend 3, dat e-bay een appstore heeft waar Silverlight apps verkocht kunnen worden en dat Silverlight 4 vandaag Release Candidate is geworden. De RTW wordt eind april verwacht, waarschijnlijk gelijk met Visual Studio 2010.

Maar de nadruk van de keynote van MIX10 lag niet op Silverlight en niet op de Expression tools. De hoofdpersoon van de avond was Windows Phone 7 series, met een uitgebreide demonstratie van de mogelijkheden van de telefoon, inclusief verschillende typen applicaties, door Joe Belfiore. ScottGu bouwde ter plekke de eerste Twitterclient voor WP7 en een collega van hem maakte binnen 8 minuten een foto-applicatie in Expression Blend 4. De Silverlight versie op WP7 is geen Silverlight lite of aparte Silverlightversie. Het is gewoon Silverlight. Alle kennis die je als developer of designer hebt opgedaan over Silverlight kan je 100% inzetten voor het maken van applicaties voor WP7. Er worden in sneltreinvaart een aantal games getoond die gemaakt zijn in XNA en gespeeld op de telefoon, de computer met de muis en een televisie met een XBox controller. Als je apps of games op WP7 wilt krijgen gaat dat via de Marketplace hub. Exacte voorwaarden worden later nader bekend gemaakt. Alle gereedschappen om Windows Phone 7 apps te maken zijn gratis beschikbaar. De ontwikkelsoftware is beschikbaar via

Na de presentatie was er tijd om even bij te praten over de nieuwe mogelijkheden. Daarna was er een live verbinding met een aantal Nederlandse bezoekers van MIX10 en de mogelijkheid om vragen te stellen en beantwoord te krijgen. In het restaurant van het Microsoft gebouw kwamen pizza’s en drankjes beschikbaar, die onder begeleiding van stevige discussies zijn verorberd. Dank Microsoft NL voor een geslaagde avond. Thuis de bits downloaden en installeren en aan de slag voor Windows Phone 7 Series met Silverlight…

ScreenMachine in Silverlight Showcase

It took a while, but my personal porftolio in Silverlight called ScreenMachine, has appeared in The Silverlight showcase. You can also reach it through the ADdendum blog, too. When you select The Netherlands as Geography in the left menu of the Showcase you can find it as fourth on the first row (for now).

ScreenMachineInShowCaseSmall Njoy!

Edit Oct 2011: The new url for the Screenmachine is :

It is placed in the News Category and it is on the 16th page or

in th Silverlight 4 Category on page 61…

Top 10 Silverlight 4 beta features for Designers

Silverlight 4 beta is out and delivers several new features for programmers, media people and designers. As a designer I was most interested in some specific features, so I’d like to share my top 10 with you.

10. Command property on buttons and hyperlink

I’ll have to explain this one. John Papa’s whitepaper only speaks of the MVVM pattern context, but in the WPF world commands are well known. Actually it is a feature not unlike Behaviors, because they encapsulate programming code in a simple property on a button or a hyperlink. The action that follows when clicking that button or hyperlink is determined by the command. Also, it is possible to include a parameter that the command can use. Thus it is used more dynamically and is more flexible. When developers create commands, designers can easily connect them as a simple property of a button or hyperlinkbutton.

<Button Content="Load" Width="120"
        Command="{Binding LoadProductsCommand}"
        CommandParameter="{Binding Path=Text, ElementName=MyFilterTextBox}"/>

9. StringFormat, TargetNullValue, FallbackValue on Data Binding

Again, maybe not straightforward, but these additions to the data binding functionality of Silverlight helps designer to format the results of data binding with more ease. TargetNullValue will show a value when the binding has null as a result, so you can insert a zero or other sensible value instead. The FallBackValue is about the same, but it shows up when a binding is unsuccessful. You can apply a different value instead. The best of the three is the StringFormat property, which allows you to format the text resulting from data binding. This way a designer can easily indicate that output is a currency or a percentage or a date in a specific format.

<TextBox Text="{Binding Path=UnitPrice, Mode=TwoWay, StringFormat=C}" />

<TextBox Text="{Binding Path=Discount, Mode=TwoWay, StringFormat=P}"/>

<TextBox Text="{Binding Path=OrderDate, Mode=TwoWay, StringFormat=’MM-dd-yyyy’}"/>

8.Webbrowser control and HTML brush

This seems like a nobrainer, but some restrictions are present. This only works in sandboxed applications, which means that you have to have an Out-Of-Browser application. You can use inline HTML (NavigateToString), an inline HTML document (Navigate) or an URL (Source).

string html = "<HTML><HEAD></HEAD><BODY style=’margin:0 padding:0′><IFRAME width=’100%’ style=’overflow: hidden;’ height=’100%’ src=’; /></BODY></HTML>";


The HTML brush lets you paint with a webpage, so you can use it as a Brush in any Shape.

<Path Data="…" >


        <HtmlBrush x:Name="htmlBrush" AlignmentX="Left" AlignmentY="Top" Stretch="None"/>



And in C# set the source: htmlBrush.SetSource(MyWebBrowser);

7. CompositeTransform

This makes a designers’ live a bit easier: combine Translation, Rotation and Scale in one go:

<Rectangle Height="100" Width="100" Fill="Red">

        <CompositeTransform ScaleX="2" Rotation="45" TranslateY="42"/>



6. Webcam and Microphone support

This one is self-explaining, but… What are designers and developers going to do with it? Check out the blog-post by Rob Houweling on the Silverlight and Expression Insiders site for details about this feature.

5. Rich Text Area control

Finally a way to create richer text experiences using the Rich Text Area. This will end the struggle with Run elements in TextBlocks to change a color, font or font size inside a text object. The Rich Text Area control welcomes every type of content. This includes other controls like Images and UI controls. Create bold, italic, colored text inside a block of text with ease using the Rich Text Area control. Will this lead to the inclusion of FlowDocuments in Silverlight one day?

4. ViewBox

A ViewBox is a handy container that allows you to scale up or down any graphic or large element that you want to display on a screen. Use the original sizes for the content and set the ViewBox to the size you want the content to show up. It’s that easy and very convenient at times. A ViewBox can contain only one element inside. It’s StretchDirection can be UpOnly, DownOnly or Both. The content can be Stretch-ed using None, Fill, Uniform and Uniform to fill, just like it’s WPF version.

<Viewbox x:Name=”iconSize” Margin="5" Width="64" Height="64">

    <Image Source="aHugeImage.png"/>


3. Fluid UI States for ItemsControl

I’d be very interested to see what designers and developer create with this feature. Create an ItemsControl and hook up interesting appearing and disappearing animations when adding or deleting items from the control. This not only allows you to animate ListBoxItems with ease, but opens the door to exiting navigation using items in ItemControls. Who’s up for the challenge? The new visual states are: BeforeLoaded, Loaded, and Unloaded.

2. Implicit Style

Styling an application helps in acceptance and defining a look for different groups of users. Implicit Styles will help a lot in implementing Themes. Actually the ToolKit people have already removed the Implicit Style Manager that took care of this. Just omit the x:Key and all controls of a the specific type will take on the style you give them. Combined with swapping ResourceDictionaries you have theming solutions available.

1. Printing support

Even though it is only possible in code, printing support is a huge improvement from a designers’ point of view. This is the most requested feature for a reason. It is possible the print the content of a page using the LayoutRoot, or any other container that you specify. It is also possible to print objects that are entirely invisible on the screen, but you’ll have to build a tree of objects in memory a feed that to the print command. This opens up enough possibilities to satisfy business consumers. So output your work to printers everywhere…

PrintDocument pd = new PrintDocument();

pd.PrintPage += (s, args) => {

    args.PageVisual = LayoutRoot;



These are the features that caught my eye as a designer. Some didn’t make it to the top ten, like the WordEllipsis TextTrimming property, Right Mouse Click Events and ScrollWheel events and ClipBoard support. Other features are more interesting for media people or developers. Check out Tim Heuer’s blog or John Papa’s white paper for all details on all new Silverlight 4 features.


Silverlight Style: GlassBorderStyle

GlassBorderStyleCreated a simple, but nice Glass Border for a panel in my current Silverlight 3 project. I’d like to share it with you…






  <Style x:Key="GlassBorderStyle" TargetType="Border">
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="Background">
            <LinearGradientBrush EndPoint="0.75,1" StartPoint="0.25,0">
                <GradientStop Color="#33FFFFFF" Offset="0"/>
                <GradientStop Color="#C0FFFFFF" Offset="0.287"/>
                <GradientStop Color="#4011322D" Offset="0.683"/>
                <GradientStop Color="#33FFFFFF" Offset="1"/>
    <Setter Property="BorderBrush">
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#5811322D" Offset="0"/>
                <GradientStop Color="#3EFFFFFF" Offset="0.25"/>
                <GradientStop Color="#FFFFFFFF" Offset="0.5"/>
                <GradientStop Color="#3EFFFFFF" Offset="0.75"/>
                <GradientStop Color="#BFFFFFFF" Offset="1"/>
    <Setter Property="Effect">
            <DropShadowEffect BlurRadius="3" ShadowDepth="3" Opacity="0.5"/>

To use this style:

<Border x:Name="GlassBorder" Height="100" Width="100" CornerRadius="10"
    Style="{StaticResource GlassBorderStyle}">
    <Button Content="OK"/>


Use initParams to swap ResourceDictionaries and load a Theme in Silverlight 3

I’ve been looking for a way the use themes just swapping ResourceDictionaries (RD’s) for some time. Now, with Silverlight 3 being able to use MergedDictionaries, this becomes possible.

It is Blendable, but you can only use RD’s with Build Action Resource and not Content. This is annoying enough to give it another go another time. You can use the workaround of using a the RD’s with build action as Resource for use with Blend only. You’ll have to change it back before you distribute your app. Want you ultimately want is to address the RD’s as Resource…

This method can help you when you:

  • want to load a theme once on application startup
  • want to set the theme as an initParam on the Silverlight plug-in
  • don’t want to use implicit styling: you’ll need two or more RD’s with identically named Styles and Resources

Restrictions of this method are:

  • Blendable using workarounds
  • You have to use one Default theme (which can have any name you want).
  • You cannot dynamically update the theme: you can set a certain theme only once at application startup.

If this is the method for you, this is what you need to do:

  • Create ResourceDictionaries for the Default theme and for one or more other themes that you want to load in the root of your Silverlight project.
  • Use x:Keys for Styles and Resources and keep them the same between RD’s.
  • Set the Build Action for these RD’s to CONTENT in Visual Studio or by editing your .CSPROJ file by hand.
  • Insert an initParam in the <Object> tag in your startup file like this:

<param name="initParams" value="Theme=TheTheme" />
  • Add a Default MergedDictionary in App.xaml:

            <ResourceDictionary Source="Default.xaml"/>

  • Declare a private currentTheme variable in App.xaml.cs

public partial class App : Application
    private string currentTheme = "Default";

  • Set the Default theme, get the initParam, make an URL to the filename and create and RD from that. Then add the RD to the MergedDictionaries:

private void Application_Startup(object sender, StartupEventArgs e)

    //set the current theme to the currentTheme variable
    string currentThemeName = string.Format("{0}.xaml", currentTheme);

    //get the theme name from the initParam
    string themeParameter = e.InitParams["Theme"];

    if (!string.IsNullOrEmpty(currentThemeName))
        //set the current theme to the theme parameter and create filename
        currentThemeName = string.Format("{0}.xaml", themeParameter);

        //create an URL from the currentThemeName
        Uri themeUrl = new Uri(currentThemeName, UriKind.RelativeOrAbsolute);

            //create a RD and set the source to the URL
            ResourceDictionary themeDictionary = new ResourceDictionary
                Source = themeUrl

            //Add the RD as a MergedDictionary
        catch (Exception ex)
            //communicate theme doesn’t exist

    this.RootVisual = new MainPage();


Many thanks to Tony Tromp and Michaud Venant for helping me out with the code.

The error “Error HRESULT E_FAIL has been returned from a call to a COM component” occurs when you forgot to change the build properties of the ResourceDictionaries to CONTENT. You can do this in Visual Studio in de Solution Explorer with the properties of the specific XAML files. This error also occurs when you maken a mistake in the name of the Theme in the initParam by messing up the quotes for example.

When you make a mistake in the Styles or the Resources used by the Styles you’ll get another error: Cannot find a Resource with the Name/Key AppBg [Line: y Position: x]. Actually if the style is OK in the Default theme it wil show that. Happily this error is easier to track and to fix, but a small error in your RD’s may have unpredictable results, so make sure they are sound.

I’ve been working with Themes from initParams for weeks. You can use Blend when you set the build action in VS to RESOURCE and restart Blend. Blend should show all the RD’s as Resources in the Resources Panel and you can edit them in the Blend artboard. You can even build in Blend and change the Theme using the initParam in the startup file. Make sure the startupfiles are the same in VS and Blend :). Before you deliver your project make sure you set the build action back to CONTENT in VS to make the theme system from initParams kick in.

I’ve placed working code on my SkyDrive.


Writeable Bitmap API heeft een parameter minder.(HBSL3 Erratum 1)

In het Handboek Silverlight 3 staat op pagina’s 155-157 de code voor een Writeable Bitmap en een Bitmap van een gedeelte van de userinterface. Deze code werkt niet goed, omdat de WriteableBitmap Class bij het aanmaken een parameter minder heeft gekregen in de definitieve versie van Silverlight 3. De PixelFormats parameter is vervallen en de bestandsindeling is nu altijd Pbgra32. Daarom moet de Writeable Bitmap iets anders geïmplementeerd worden. Bovendien zijn de Lock() en Unlock() methodes vervallen, maar het is nog steeds nodig om Invalidate() aan te roepen.

Bij aanmaken van een WriteableBitmap moet in plaats van…

private void WriteBitmap()
    const int imageWidth = 200;
    const int imageHeight = 200;
    WriteableBitmap wbm = new WriteableBitmap(
        imageWidth, imageHeight, PixelFormats.Bgr32);
    for (int x = 0; x < imageWidth; x++)
        for (int y = 0; y < imageHeight; y++)
            // genereer een kleur in Pbgra32 format
            byte[] components = new byte[4];
            components[0] = (byte)(x % 255); // blauw
            components[1] = (byte)(y % 255); // groen
            components[2] = (byte)(x * y % 255); // rood
            components[3] = 0; // alpha transparantie
            int pixelValue = BitConverter.ToInt32(components, 0);

            // zet de waarde van de pixels
            wbm[y * imageWidth + x] = pixelValue;
    TheBitmap.Source = wbm;

…er dit staan:

private void WriteBitmap()
    const int imageWidth = 200;
    const int imageHeight = 200;
    WriteableBitmap wbm = new WriteableBitmap(imageWidth, imageHeight);
    for (int x = 0; x < imageWidth; x++)
        for (int y = 0; y < imageHeight; y++)
            // genereer een kleur in Pbgra32 format
            byte[] components = new byte[4];
            components[0] = (byte)(x % 255); // blauw
            components[1] = (byte)(y % 255); // groen
            components[2] = (byte)(x * y % 255); // rood
            components[3] = 255; // alpha transparantie
            int pixelValue = BitConverter.ToInt32(components, 0);

            // zet de waarde van de pixels
            wbm.Pixels[y * imageWidth + x] = pixelValue; 
    // zet de source van de afbeelding en teken opnieuw.
    TheBitmap.Source = wbm;

Bij het vastleggen van een deel van de userinterface in een WriteableBitmap moet in plaats van…

<Grid x:Name="TheGrid">

wbmUI = new WriteableBitmap((int) TheGrid.RenderSize.Width, (int) TheGrid.RenderSize.Height, PixelFormats.Bgr32);
wbmUI.Render(TheGrid, new TranslateTransform());
imgResult.Content = new Image() { Source = wbmUI };

…er dit staan:

WriteableBitmap wbmUI = new WriteableBitmap((int) TheGrid.RenderSize.Width,(int) TheGrid.RenderSize.Height);

wbmUI.Render(TheGrid, null);
imgResult.Content = new Image() { Source = wbmUI };

Njoy Writeable Bitmaps!

10 Silverlight loading animations using percentages (HBSL3 Addendum 1)

Following Mike Taulty’s rant avoiding the “Blue Balls” when loading a Silverlight application, I’ve been thinking about what ways you’d have to show a loading animation (a.k.a. Splash Screen 🙂 using the progress percentage in a meaningful way.

The idea was to come up with 10 way to do this and it proved to be harder than I thought. I’ve made a little sketch that is a little further down this post, but first let’s have a look at how to show this. Actually is it XAML only, because the application is not loaded yet, so it can only use Javascript code behind. Creating a XAML-file and a JS-file in your Web project is enough.

Create a new XAML file called SplashScreen.xaml without code behind and a Grid or Canvas as the outer container. Place a Textbox to show a percentage and some Rectangles to show the progress.

    xmlns="<a href=";">"</a>
    xmlns:x="<a href=";">"</a>
    Width="640" Height="480" Background="White">
  <Canvas Canvas.Top="100" Canvas.Left="100" Width="440" Height="280">
    <Rectangle x:Name="rctProgressBarTrack" Width="300" Height="25" Canvas.Top="50" Canvas.Left="10" Fill="Silver" />
    <Rectangle x:Name="rctProgressBar" Width="300" Height="25" Canvas.Top="50" Canvas.Left="10" Fill="Red">
          <ScaleTransform x:Name="rctProgress" ScaleX="0" ScaleY="1"/>
    <TextBlock x:Name="txtStatus" Height="20" Canvas.Top="55" Canvas.Left="125" Text="Loading: " TextWrapping="Wrap"/>

In your startup file in the Web project add two lines to the Silverlight plug-in:

<param name="splashScreenSource" value="SplashScreen.xaml"/>
    value="onSourceDownloadProgressChanged" />

Create a small SplashScreen.js file in your Web project containing only this:

function onSourceDownloadProgressChanged(sender, eventArgs) {
    sender.findName("txtStatus").Text =
        "Loading: " + Math.round((eventArgs.progress * 1000)) / 10 + "%";
    sender.findName("rctProgress").ScaleY = eventArgs.progress;

Now copy the SplashScreen.xaml file to your Web project. If you change it later, don’t forget to copy it into your XAML project again . You may want to create something in your MainPage.xaml so there’s something to show after loading…


LoadingAnimations Here are  a 10 ideas for creating interesting loading animations. Most a using the progress percentage in some way. A few are “indeterminate” so, they could run forever. Note that the last 2 are dynamic, so should update every second or so. You can use the bars to fill other paths too, like coffee cups. You may need to scale a Clipping Mask for that.

Don’t make a Splash Screen that needs it’s own loading animation 🙂


Change FontSize with ElementBinding

Jakob Nielsen says: “Let users control font size”. Unfortunately in Silverlight the nice features of the WPF FlowDocument control are not available (yet). You cannot use the automatic font size feature of that control in a Silverlight app. But in Silverlight 3 ElementBinding enables you to bind a value to the FontSize attribute of a TextBlock. Using a Converter with a ConverterParameter, dynamic font size becomes available:

Click for working version...

The trick is to use TextBlock controls for your text and set it’s properties in a Style, like you would normally do. This time, leave the FontSize attribute out.

<Style x:Key=”Body” TargetType=”TextBlock”>
    <Setter Property=”FontFamily” Value=”Trebuchet MS” />
    <Setter Property=”TextWrapping” Value=”Wrap” />
<Style x:Key=”Header” TargetType=”TextBlock” BasedOn=”{StaticResource Body}”>
    <Setter Property=”FontWeight” Value=”Bold” />
<Style x:Key=”Caption” TargetType=”TextBlock” BasedOn=”{StaticResource Body}”>
    <Setter Property=”FontStyle” Value=”Italic” />
    <Setter Property=”Foreground” Value=”Gray” />

Create TextBlocks with these Styles and Text, but set the FontSize attribute to an ElementBinding with the Value of a small Slider.

<TextBlock x:Name=”txtHeader1″ Style=”{StaticResource Header}”  FontSize=”{Binding Value, ElementName=Slider, Converter={StaticResource FontSizeConverter}, ConverterParameter=H1}” Text=”Header 1″/>

<Slider x:Name=”Slider” Value=”10″ SmallChange=”1″ LargeChange=”12″ Minimum=”6″ Maximum=”72″ Width=”100″ />

The converter will set the FontSize for you. The ConverterParameter has string values from “H1” to “H7”, like you would use in HTML. You can set this to any string you like, but these seem to make sense…

The converter looks like this:

using System;
using System.Windows.Data;

namespace Converters
    public class FontSizeConverter : IValueConverter  
        public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)  
            double v = (double)value;

            if (parameter != null)
                string fontSizeString = parameter.ToString();
                if (!string.IsNullOrEmpty(fontSizeString))
                        case “H1” :
                            value = 2.4 * v;
                        case “H2” :
                            value = 1.8 * v;
                        case “H3” :
                            value = 1.4 * v;
                        case “H4” :
                            value = 1.2 * v;
                        case “H5” :
                            value = 1 * v;
                        case “H6” :
                            value = .8 * v;
                        case “H7″ :
                            value = .6 * v;
            value = System.Convert.ToInt32(value); // we need an integer, not double…
            return value.ToString(); // …but as a string

As you can see the value is updated with different multipliers, depending on the header parameter you pass in. H5 is the basic text size, used by the Body Text, so its multiplier is 1. You can play with these multipliers if you want a different effect.

Add the namespace to your XAML file and put the converter as a resource at the top of the file…

<UserControl x:Class=”ControlFontSize.MainPage”
        <cvs:FontSizeConverter x:Key=”FontSizeConverter” />

… and you’re good to go. Let users control text size!

Working code is on my SkyDrive… Njoy!

Handboek Silverlight 3!

9789059403888klein_thumb.jpgEind augustus is het Handboek Silverlight 3 uitgebracht. Het eerste en vooralsnog enige boek over Silverlight 3 in het Nederlands.

Silverlight is de spannende, nieuwe techniek om met behulp van vectorafbeeldingen websites en -applicaties te creëren. Hierdoor worden visuele elementen haarscherp getoond en zijn ze schaalbaar, terwijl het downloaden sneller gaat dan bij bitmapafbeeldingen. De capaciteiten voor transparantie, kleurverlopen, animatie en 3D-projectie bieden u de kans om indrukwekkende ontwerpen te realiseren.

Wilt u een Silverlight-project van begin tot eind doorlopen, dan is dit boek voor u. Vier fasen in het proces van het creëren van een Silverlight-applicatie komen uitgebreid aan de orde:

  • Ontwerpen: over creativiteit, concept, schetsen en de gereedschappen SketchFlow en Expression Design.
  • Produceren: over XAML en de gereedschappen Expression Blend, Expression Encoder en Deep Zoom.
  • Programmeren: over de programmeeromgeving Visual Studio, aangevuld met een aantal praktische toepassingen in C#.
  • Publiceren: over het online brengen van Silverlight-sites en -applicaties, waaronder zoekmachineoptimalisatie, aangepaste installatie en uitrol in een zakelijke omgeving.

Webdesigners leren werken met eXtensible Application Markup Language (XAML), programmeurs leren hoe Silverlight aansluit op C# en het .NET-platform en ontwerpers leren hoe de grafische gereedschappen voor Silverlight precies werken. Dit boek bevat talloze bruikbare oplossingen voor problemen die u bij uw Silverlight-projecten tegen kunt komen.

Microsoft staat pal achter deze techniek en neemt het op in eigen websites, nieuwe platformen en toekomstige ontwikkelingen. Silverlight kunt u in de browser draaien, op de desktop installeren en het is onderdeel van de komende versie van SharePoint. De markuptaal XAML is niet alleen onderdeel van Silverlight, maar ook van Windows Presentation Foundation voor Windows-applicaties en van Microsoft Surface, de multi-touch tafelcomputer. Uw kennis van XAML kunt u op deze platformen ook toepassen.

Bestel ‘m alvast bij je favoriete boekhandel online:

Meer informatie vindt je bij de uitgever, Van Duuren Media.

How to place a vector illustration in Silverlight 2 Application Resources

Recently, I did a presentation on how to structure a Silverlight Application using Styles and Resources. This covered several topics about structuring XAML using only the Blend User Interface as a tool.

When you create a Style, Blend goes in Style Recording mode (even though there is no visual indication of that) and all properties you set in this mode are collected in your styles automatically. Just remember to begin creating a Style, you can’t convert inline properties to styles momentarily.

You can create a Resource from almost everything (although you cannot always use them as such) using the small square to the right of the input box for the property in the Property Panel. Using the Resource Panel in Blend reorganizing Resources is straightforward. You can even move User Control Resources to the application level by dragging the layer to the Application Resource Dictionary in the Resource panel.

Placing animations in App. xaml is certainly possible with the technique I mentioned earlier. You’ll have to start the animation using code.

All this helps to set up a more structured version of your Silverlight Application. But… One thing missing from this list is how to remove large vector illustrations in XAML from you pages and place them as a resource in the application level. That way large chunks of XAML are out of the way and they can be reused using only one line of code: efficient and good for your application’s performance. With the following technique, you can put ANY large, coherent piece of XAML away as a resource. Anything that you can stash in a Grid panel, for example.

The trick is the use of a Content Control and to set it’s Template property to a ControlTemplate that is used as a Resource:

<ContentControl Template="{StaticResource ctpBullet}" />


      <ControlTemplate x:Name="ctpBullet" TargetType="ContentControl">
            <Grid Width="12" Height="12" VerticalAlignment="Top" HorizontalAlignment="Center">
                    <RowDefinition />
                    <RowDefinition />
                <Ellipse x:Name="Bullet" Grid.RowSpan="2" Stretch="Fill" StrokeThickness="0.5" StrokeLineJoin="Round" Stroke="#FF870000">
                        <RadialGradientBrush RadiusX="0.67158" RadiusY="0.671574" Center="0.34738,0.263298" GradientOrigin="0.34738,0.263298">
                                <GradientStop Color="#FFFFFFFF" Offset="0"/>
                                <GradientStop Color="#FFFF0000" Offset="0.512712"/>
                                <GradientStop Color="#FFCF0000" Offset="0.817797"/>
                                <GradientStop Color="#FFFF0000" Offset="1"/>
                                    <RotateTransform CenterX="0.34738" CenterY="0.263298" Angle="57.8044"/>
                <Path x:Name="BulletGlow" Margin="2" Stretch="Fill" Data="F1 M 23.0627,100.787C 26.3052,100.787 28.9338,103.416 28.9338,106.659C 28.9338,109.901 26.3052,106.595 23.0627,106.595C 19.8202,106.595 17.1916,109.901 17.1916,106.659C 17.1916,103.416 19.8202,100.787 23.0627,100.787 Z ">
                        <RadialGradientBrush RadiusX="1.19041" RadiusY="0.858456" Center="0.332587,0.223982" GradientOrigin="0.332587,0.223982">
                                <GradientStop Color="#FFFED4D0" Offset="0"/>
                                <GradientStop Color="#FFF27037" Offset="1"/>
                                    <SkewTransform CenterX="0.332587" CenterY="0.223982" AngleX="22.4347" AngleY="0"/>
                                    <RotateTransform CenterX="0.332587" CenterY="0.223982" Angle="71.469"/>

So, clean up your XAML markup. With this trick you can remove those large vector illustrations from you screen layout and place them out of the way in app.xaml.


Intellisense for Expression Blend 2 SP1 working again!

Tonight I found this short cryptic message by Bennage on the MSDN Code Gallery site:

Blend 2.0 SP1
Oct 1 at 4:37 PM 
FYI I was able to get the plugin working against 2.0 sp1 simply by recompiling the source against the 2.0 sp1 assemblies.

As a designer, it was a bit too short and cryptic for me. But I decided to have a go anyway. This it what I had to do do make Intellisense working again for Blend 2 SP1:

  1. Download the original from the MSDN Code Gallery site:
  2. Install the Addin as explained on the Homepage:
    Blend.bat, Addins folder with a DLL and the Schemas Subfolder should all be in place. If you have a failed attempt to install BlendSense for Blend 2 SP1, you’ll probably be in good shape 😉
  3. Download the Code from the MSDN Code Gallery site:
  4. Upzip it to your visual studio or Blend projects directory:
    c:\users\YOU\Documents\Expression\Expression Blend Projects
  5. Start Visual Studio or Expression Blend and load the Expression.Blend.Intellisense project
  6. Open the Solution Explorer or Project tab and check the References  folder to find several dll’s that are missing or invalid, marked by a yellow exclamation mark
  7. Right-click on the References folder and select Add Reference…
    Click the Browse tab in the Add Reference dialogbox and browse to your Blend 2 SP1 location: “c:\program files\Microsoft Expression\Blend 2”
  8. Select all the DLL files that are missing by keeping the Ctrl key down while clicking the filenames. Click OK. The yellow exclamation marks in the Solution Explorer or Project tab References folder will disappear.
  9. Build the project using Build/Rebuild Solution. If all is well, the build will succeed.
  10. Check the debug folder in de Expression.Blend.Intellisense folder for a DLL called Expression.Blend.Intellisense.dll (if you made a release build you’ll find it in the Release folder of course).
  11. Copy this file to the Add-In folder in the Expression Blend program folder: “c:\program files\Microsoft Expression\Blend 2\Addins” Replace the existing file with the same name but smaller in size with this new DLL. Don’t paste it in the Blend program folder, but in de Add-in folder.
  12. Run Blend.bat from the Blend Program folder.
    This contains the command:
    start Blend.exe -addin:Addins\Expression.Blend.Intellisense.dll
  13. Blend wil start and ask you to open your last project. Open the project.
    Press F11 twice or click the XAML tab at the top right of the working area in Blend.
  14. Press Ctrl + Spacebar inside any XAML statement to find intellisense working!

Thanks bennage for the original post at: and of course many, many thanks to Stefan Dobrev for making it all possible at

Hope this helps (I know it will!) Njoy!

Silverlight Animations as Application Resources in app.xaml

I like to have my animations apart from the rest of the XAML, because they can become very lengthy and are not really relevant to the functionality of the UI. It’s better to edit them separately.

The animations in Silverlight have to be started using Event Handlers in a Code Behind file in Silverlight instead of the Triggers used in WPF. The Triggers were able to connect to the target object for an animation. The Event Handlers won’t do that for you.

You’ll have to find the Animation Resource, assign it to a Storyboard object in the Code Behind file of your page and set the Target element for that Storyboard before starting the animation.

Michel Heijman helped me out with this. This is his solution:

Create a helper class that can find Resources for you (like in WPF). Save this in the root of your project and name it ResourceLocator.cs.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace AnimationsAsApplicationResources
    public static class ResourceLocator

        /// Helper method for finding resources located in app.xaml

        ///         ///
        public static object FindResource(string name)
            if (App.Current.Resources.Contains(name))
                return App.Current.Resources[name];
                FrameworkElement root = App.Current.RootVisual as FrameworkElement;
                return root.FindName(name);

In the Code Behind of your page, add the following to access the Animation Resource, set the TargetName for it and to run the Animation:

        private void startStoryboard1(object sender, RoutedEventArgs e)
            // find the storyboard with helper class:
            Storyboard Storyboard1Resource = ResourceLocator.FindResource(“Storyboard1” ) as Storyboard;
            if (Storyboard1Resource != null)
                // Set target for storyboard:
                Storyboard.SetTarget(Storyboard1Resource, Rectangle1);
                // Begin storyboard:

Don’t forget to place your animation in app.xaml now 🙂 No need to change the app.xaml.cs file for this…


Silverlight 2 beta 2 dropshadows using Blends

Lacking the DropShadow BitmapEffect that is present in Windows Presentation Foundation, we cannot use BitmapEffects to create shadows for containers. This doesn’t mean no shadows are possible in Silverlight 2. In the old days of CorelDraw 5 we used so-called Blends to create shadows in vector drawings. Blends are a feature that morphs one shape to another using several steps. In these steps new shapes are created that are in-between the starting and the resulting shape. Actually I think Expression Design does Blending. Just make sure the program can guess which vertices it can map to vertices on the resulting shape. If you don´t your shapes go haywire :).

Using XAML you can emulate Blends in vector drawing programs. Below is a piece of code that mimicks Blends. Note that the Margin used is always 1 to ensure a smooth gradient. Note too, that the used color is almost transparant Black. These transparent colors add up to a nice shade of gray. If you want to have a darker shadow, just make this color darker. I have not used Resources just to keep the XAML concise, but I would make editing the Shadow color easier. Actually, you can make a UserControl like a ShadowBorder that not only allows for changing the shadow color, but also the shadow direction. Anyone who makes a user friendly control like that, please let me know…

<Grid x:Name="LayoutRoot" Background="LightYellow" >
 <Grid  Width="300" Height="200">
  <Border CornerRadius="25" Margin="1" Background="#03000000">
  <Border CornerRadius="24" Margin="1" Background="#03000000">
  <Border CornerRadius="23" Margin="1" Background="#03000000">
  <Border CornerRadius="22" Margin="1" Background="#03000000">
  <Border CornerRadius="21" Margin="1" Background="#03000000">
  <Border CornerRadius="20" Margin="1" Background="#03000000">
  <Border CornerRadius="19" Margin="1" Background="#03000000">
  <Border CornerRadius="18" Margin="1" Background="#03000000">
  <Border CornerRadius="17" Margin="1" Background="#03000000">
  <Border CornerRadius="16" Margin="1" Background="#03000000">
  <Border CornerRadius="15" Margin="1" Background="#FFFFFFFF" />
  <Grid Margin="12" VerticalAlignment="Center" HorizontalAlignment="Center" >
   <TextBlock Foreground="Silver" Text="Your content here..." />


Color Palettes using Color Resources in Silverlight

I’ve been asked by a client if it was possible to make color versions of a design. I told him that that was actually very easy. And it is. It is just that you have to treat your colors a little different: you’ll have to create color palettes using Color Resources. Because that worked a little different in Silverlight 2 Beta 1 than in WPF I was on the wrong foot for a long time. Finally I worked it out and here it is:

There’s only one way to specify a Color in Silverlight:

<Color x:Key="colAccent">#FF800000</Color>

and this gets underlined in Visual Studio indicating that Color cannot have direct content (meaning the color code between the <Color> and </Color> tags). You’ll have to ignore that 🙂

All other ways to specify color won’t work in Silverlight:

  <!-- Colors in Silverlight 2 beta 2:-->
        <!-- all these don't work -->
        <!--<Color x:Key="colBrightAccent" A="FF" R="00" G="00" B="00" />-->
        <!--<Color x:Key="colBrightAccent" A="#FF" R="#00" G="#00" B="#00" />-->
        <!-- <Color x:Key="colBrightAccent" A="255" R="255" G="0" B="0" />-->
        <!--<Color x:Key="colBrightAccent" scA="1" scR="0" scG="0" scB="0" />-->

Note that at least the second and the fourth are valid in WPF. The third seems to go well in Blend, but gives an error in the browser and won’t show anything: the screen remains white.

Still, this allows you to create palettes of color. Here’s one with two colors:

<Color x:Key="colAccent">#FF800000</Color>
<Color x:Key="colBrightAccent">#FFFF0000</Color>


You can use these in SolidColorBrushes and LinearGradienBrushes like these:

        <!-- Brushes that can apply those colors using color resources -->
        <SolidColorBrush x:Key="brAccent" Color="{StaticResource colAccent}" />
        <SolidColorBrush x:Key="brBrightAccent" Color="{StaticResource colBrightAccent}" />

        <!--Gradient Brushes can use those colors too! -->
        <LinearGradientBrush x:Key="lgbrAccent" StartPoint="0.5,0" EndPoint="0.5,1">
            <GradientStop Color="{StaticResource colBrightAccent}" Offset="0" />
            <GradientStop Color="{StaticResource colAccent}" Offset="1" />

Place all this in app.xaml between de <Application.Resources> tags and you’ll be ready to apply them in some normal XAML:

 <Grid x:Name="LayoutRoot" Width="200" Height="150">
   <RowDefinition /><RowDefinition /><RowDefinition />
  <Rectangle Grid.Row="0" Fill="{StaticResource brAccent}" Stroke="{StaticResource brBrightAccent}" RadiusY="25" RadiusX="25" StrokeThickness="5"/>
  <Rectangle Grid.Row="1" Fill="{StaticResource brBrightAccent}" Stroke="{StaticResource brAccent}" RadiusY="25" RadiusX="25" StrokeThickness="5"/>
  <Rectangle Grid.Row="2" Fill="{StaticResource lgbrAccent}" Stroke="{StaticResource brAccent}" RadiusX="25" RadiusY="25" StrokeThickness="5" /> 

What makes it easy to make color versions of a design is the fact that you can easily replace the two color codes in the Palette to change the look of the entire application! This would do the trick:

  <Color x:Key="colAccent">#FF008000</Color>
  <Color x:Key="colBrightAccent">#FF00FF00</Color>

Be aware of the use of a Color Resource (colBright) in a LinearGradientBrush, but a Brush Resource (brBright) when you use it for a Fill or a Stroke.

So with about 10 colors as resource in app.xaml, you can actually create a basis for skinning your application. It’s just that now I still have to replace all the separated colors in my project with StaticResources and that will take some time… So now it is easy, but it will take a while 🙂 If you remember to work like this from scratch, you’ll be fine when a client ask you if color versions are possible…


Using the Blend Visual State Manager (VSM) on the MediaPlayer-style VideoButton

 Last weekend I played around with the new version of Blend 2.5 to see how the Visual State Manager (VSM) was working. I was pleasantly surprised by the simplicity of it all. Actually it works just like an animation. You just don’t need a timeline for states. So if you know how to animate in Blend, it is fairly easy to add states to buttons. To show you, I’ve adde states to the MediaPlayer-style videobutton I made in the previous post.

First doubleclick the button in the Objects and Timeline category in the Interaction Panel. A yellow line indicates it is selected. Then from the Button in the breadcrumbsbar below the titel of the document, click the little arrow and select Edit ControlParts (Template) and Edit Template. Since we’re using a button with a self-made template we already have a template. If you start with a new button, you’ll have to create a template using the menu first.

In the button Template, the States Category in the Interaction Panel will show several default states for the button. Below,  I’ve selected the pressed state. The “State Recording is on” message appears in red and just like in animating, you can now change Opacity, Color for that state. You can even use transformation, as you may notice that the glow and the TextBlock are moved down a few pixels.

The Name of the elements of the button in the Templates are preceded by a red circle with a white arrow to indicate it is particitpating in the current state. I have not discovered how to delete this using the UI, but you can easily find it in the XAML is you have to.

You can add transitions for the several states of this button using the + icons and – icons on the State bars. Change the transistion time with the (as buttons disguised) TextBoxes. You can drag to change the value like in other TextBoxes in Blend.

These are the states I created: a lighter yellow for the MouseOver, a darker yellow and transitions on the glow and text for the Pressed and a colorless version for the Disabled state. Note the the Focus state kicks in when the button is Pressen and remains Focused when released…













The XAML that the VSM generates is rather lengthy. Just as an example here’s the state which has least code (except for the Normal state that has an empty Storyboard)…

        <vsm:VisualStateGroup x:Name="CommonStates">
          <vsm:VisualTransition Duration="0:0:0.2" To="MouseOver"/>
          <vsm:VisualTransition Duration="0:0:0.1" To="Pressed"/>

         <vsm:VisualState x:Name="Normal">

         <vsm:VisualState x:Name="MouseOver">
           <ColorAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;2&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="0" Value="#FFFFFB93"/>
           <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;0&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFEFF77"/>
           <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;1&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFDB005"/>