Setting visibility based on wp7 themes
Intro
The Technical Certification Requirements for Windows Phone 7 applications state the following:
5.5.2 – Content and Themes
Application content, such as text and visual elements, must be visible and legible regardless of the phone theme. For example, if the phone theme changes from black background to white background, the text and visual elements of your application must be visible or legible.
This means that everything in you application, including images, should be well visible in the dark and light theming of the phone. Handling dark/light support is very easy.
Dark and Light
Often companies have a special version of their logos for different situations (Bing for example). For this demo I’ve created two logos, a black and a white one. The white logo should be used when the theme is set to dark, the other when a light theme has been selected.
I’ve dropped these images into Expression Blend and grouped them together in a Grid control (Ctrl+G ). This grid is placed in the title panel, which resulted in the following XAML:
<StackPanel x:Name="TitlePanel" Grid.Row="0">
<Grid>
<Image Source="Logo-Black.png" />
<Image Source="Logo-White.png" />
</Grid>
</StackPanel>
To get the white logo to be only visible when the dark theme is set, select the image of the white logo. With the image selected click on the “Advanced options”-peg:

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

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

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

Wrap-up
Setting the visibility like this can be done on every element in your XAML. And whenever you need to use the visibility for other purposes, there’s a similar resource for the Opacity.
Discovering Expression Blend 5 – ListView
Often you need to display a list of items in a application. The Windows Library for JavaScript contains a ListView control for you to use in your applications. The control can be bound to a data source and templated from HTML.
Getting started
We’ll start off by creating a new project and choosing the Fixed Layout Application project template.
As you can see, the template has added a paragraph (p) to the tree which contains some text. You can use that to place the title of your application. The ListView is going to be in the same div as that paragraph.
You can add the ListView by hand, typing the HTML, but I personally prefer dragging and dropping controls onto the designer. Select the parent div of the paragraph. 
Type ListView in the search box of the Assets panel and drag the result from the list to the design surface.

If you switch to Split view in the designer you can see the HTML …
which should contain the following element.
<div data-win-control="WinJS.UI.ListView"></div>
To be able to write code against the ListView it has to have an Id. You can enter this on the Attributes panel. In this case I named the ListView “posts”.

Getting Data
The ListView in this demo application is going to display the Atom feed from this blog. The Windows Library makes this very easy.
Have a look at default.js in your solution. This file contains some code to get you started. When the window is activated the onmainwindowsactivated function is called. This is where the retrieval of the atom feed has to be initiated. First create a new AtomPubClient and a Uri to the feed. Than, pass the url to the retreiveFeedAsync function and have it process the posts or handle the error. At the end of the function you have to call processAll to have all declarative bindings applied on the controls. This is needed to get the templating to work which we’ll create in a second.
I haven’t implemented error handling in the demo, only an empty function. The processPosts function will be implemented after the templated.
WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind ===
Windows.ApplicationModel.Activation.ActivationKind.launch) {
var syn = new Windows.Web.AtomPub.AtomPubClientClient();
var url =
new Windows.Foundation.Uri("http://timmykokke.com/atom");
syn.retrieveFeedAsync(url)
.then(processPosts, downloadError);
WinJS.UI.processAll();
}
}
function downloadError() {
// handle error
}
Creating a template
The template is created in HTML. It’s basically a div with the data-win-control set like the ListView. The children of that div are used as a template for the ListView. The template has to be defined before the ListView. To get the bindings to work you’ll have to add the binding.js script to the head section of the HTML file.
The actual binding is done by adding the data-win-control attribute to the divs inside the template. In this case the innerText property of the div is bound to the title property of the data bound object. Note that the children of the template are not shown in the Live DOM panel.
I’ll demonstrate how to set the classes later.
<script src="/winjs/js/binding.js"></script>
...
<div id="itemTemplate" data-win-control="WinJS.Binding.Template" >
<div class="post">
<div class="title" data-win-bind="innerText: title"></div>
<div class="summary" data-win-bind="innerText: summary"></div>
<div class="date" data-win-bind="innerText: date"></div>
</div>
</div>
<div id="posts" data-win-control="WinJS.UI.ListView" ></div>
To make the template known to the ListView, select it and go to the Attributes panel. Enter the name of the template in the textbox next to the itemRenderer property. In this case the templated is named itemTemplate.

Process feed
The feed returned by the earlier code has to be processed to match the template. It’s nothing more than creating an array (myDataSource), run over the items, adding anonymous objects to the array and setting the data source of the posts to it. If you would like to do some custom formatting on the items, like changing the date to something more readable for example, you can do that here.
function processPosts(feed) {
var myDataSource = [];
for (var i = 0, len = feed.items.length; i < len; i++) {
var item = feed.items[i];
myDataSource.push({
title: item.title.text,
summary: item.summary.text,
date: item.publishedDate
});
}
posts.winControl.dataSource = myDataSource;
}
One of the great things of working with Blend is that you do not have to run your application to see the result and work with it. Try hitting CTRL+R or click on the refresh button in the top right corner of the designer.
If all code is correct you should see the ListView filled with titles and summaries. The Live DOM panel should be filled with elements now. The elements that are generated by code are added to the list to. These elements are marked with a small lightning bold icon.

Now we have to make sure the ListView is showing a ListLayout. With the posts element selected in the Live DOM panel head over to the Attributes panel. Look for the layout property and hit the button next to it.

Select ListLayout from the list and hit Ok. Refresh the design if needed.

CSS for template
Now we have the ListView filled with data we can set the templates.
Try selecting a title of one of the posts. You might have to click a couple of times, and notice that with every click you drill a little deeper in the element tree.

With the element selected head over to the CSS Properties panel. Click on the little triangle and select Create style rule from selected element class… and title.

This will create a CSS style rule in default.css for the title class. It is automatically selected. Try changing some of its properties, for example the text color and font-size and see what happens. The height and margins of the programmatically added items is not recalculated on every change, so you may want to hit the refresh button every now and then to update it.
You can repeat the process for the summary and date template items too.
To see what items in the designer are affected by a CSS style rule, select one on the Styles panel. For example the .title rule. Notice how all titles got a green border in the designer and the elements in the Live DOM panel got a dark green background.
Wrap up
I hope that this tutorial has given you a start on how to use the ListView and how to use templating in Expression Blend. Other controls work in pretty much the same way. Feel free to drop my a line if you have any questions regarding this tutorial or anything else you run into.
For future tutorials on Expression Blend please subscribe to the rss feed or follow me on Twitter (@Sorskoot).
Discovering Expression Blend 5 – Styles
In my previous article I explained the different templates of the Expression Blend 5 preview. Today I would like to walk you through some of the basic of using CSS, or Cascading Style Sheets, in Expression Blend 5. You’ll need CSS to define the look and formatting of your Windows 8 Metro Style application. Expression Blend 5 helps you create your styles in pretty much the same way you are used to when working on Silverlight or WPF applications in Expression Blend 4 and earlier. But not entirely.
Defining a style
For sake of simplicity I’ve created a new solution in Blend using the Blank Application project template. This template comes with three CSS files. Two files are for the default Metro style. One defines a light UI, ui-light.css and one that defines a dark UI, ui-dark.css. Only one of these files is linked in the default.html file, the dark version. I won’t recommend changing these files, but adding you own styles to a new CSS file or adding them to the third CSS file in the project, default.css.
Style sheets linked to the currently opened and active file can be found on the Styles panel.

On this panel you can quickly create new style sheets, link existing CSS files or add a style block to you html file. You can also add new style rules to a style sheet. Because there can be a large amount of style rules available a search box is available to help you find your rules very fast.
We’ll start by adding a rule to the default.css file by clicking on the “ + “ symbol next at the end of the line.

The style sheet unfolds and a new rule is added to the list. Type #YellowHeader and hit enter. The “ # “ indicates this rule will be applied to an html element with YellowHeader as its ID.

Setting Properties
With the newly added style rule selected have a look at the CSS Properties panel. At the top of panel you’ll find the name of the rule, in this case #YellowHeader. Below that is a search box to find properties. A checkbox for filtering the list is next. Check this to hide all empty properties and show only the ones that are set to certain value. The last part of the CSS Properties panel show a list of all available CSS properties. You can group these per category or show them as a long list ordered by name.

As the name of the style rule implies, we’re going to make a header that is yellow. Navigate to the Text category and click on big box next to color. The Color Editor pops out where you can select a color. Pick yellow. Note that the little square at the end of the line becomes white indicating a value has been set, different from the default.

Apply Rule
Now we’ve got a style rule defined we’ll need to add it an html element. We’re going to apply this to an H1 tag in the html file. Set the designer to split view to be able to edit the raw html by clicking on the little split button on the upper right corner of the design panel.
Add the following between the start and end of the Body tag:
<H1>A Yellow Header</H1>
The element immediately shows up in the designer and the Live DOM panel too.
Select the element in the Live Dom panel or in the designer. And look at the Attributes panel now. This panel contains all attributes for the selected html element. All elements can have an id which uniquely identifies the element. To match this with CSS rule we’ve created earlier name it YellowHeader. Notice that in the list of attributes the id changes too, the little square becomes white and the id also shows up in the Live DOM panel.

Because we’ve created the rule before setting the id, the H1 element immediately turns to yellow.

One last great feature that was added is to quickly find out which elements are affected by a certain style rule. Select the #YellowHeader rule on the Styles panel and watch the border around the selected element in the designer turn green. Notice the element in the Live DOM getting a dark green background also.
Inline Styles
There’s more… In this case we’re going to work the other way around. We’ll start with some html elements and add styles for that.
Start by adding the following lines to the body of the html file, right below the H1 tag we added earlier.
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
This creates a list with 3 items.
Select the first LI element. On the CSS Properties panel, have a look at the Applied Rules box. Because the styles are cascading and this stack of applied rules can grow bug, it’s sometimes hard to find out what’s the winning rule. This box helps you with that. When winning is selected the properties show what properties are set. Try selecting the bottom one in this case and note all three items are surrounded with a green border again. This is because the selected rule is applied on all LI tags.
Select inline in the Applied Rules box to create an inline style. When this is selected, the changes you make to the properties are placed inside the html tags.

Lets change a couple of properties:
- Set background-color to dark blue
- Set font-size to 15pt
- Set font-weight to bold
- Set line-height to 25pt
The item should look something like this now:

CSS Class
Very often CSS uses classes (not .NET classes with code, but CSS classes) to define the looks and formatting for multiple elements at once. Lets convert the previously created inline style to a class and apply it to the other list items.
With the second LI element selected go to the Attributes panel and write redItem in the textbox behind class.

Next, switch to the CSS Properties panel. Click on the little tiny triangle in the upper right corner of the Applied Rules and select Create style rule from selected element class… –> redItem.

Change the text-color to red, the line-height to 25pt and the background-color to dark red.

Select the third LI element now and go to the Attributes panel again. Enter redItem in the box behind class and watch the third item turn red too. Try selecting the .redItem rule on the Styles panel too and notice both elements get a green border.
Wrap up
I hope you get the basic idea of how to work with CSS styles in Expression Blend 5. If you haven’t used CSS before, have a look over at www.w3schools.com. You’ll find lots of information there about CSS and CSS3, along with much more information about other web development/design topic.
For future tutorials on Expression Blend (and I’m sure many will follow) please subscribe to the rss feed or follow me on Twitter (@Sorskoot).
Discovering Expression Blend 5 – Templates
At the BUILD event a lot of great applications were released. The big one of course was the Windows 8 preview. One of the released ISOs contains a couple of preview version of development tools. Expression Blend 5 preview is one of them.
This preview of Expression Blend 5 doesn’t let you create Silverlight, WPF or Windows Phone 7 apps. Instead it does what a lot of people where hoping for: Editing/Designing Html5, Css and JavaScript.
Project Templates
The first thing to notice are the new project templates. There’s only one category in the preview: Windows Metro Style. The category contains 5 templates. All templates help you getting started creating Html applications for Windows 8 in Metro style. The Language and Version dropdown lists only contain one element in the preview version. I assume these will grow over time, when Silverlight, WPF and WP7 return.
The Blank Application template creates a solutions with only the minimal elements needed. The designer shows a tablet-shape around the surface, like you might be used to when working on Windows Phone 7 applications. The solution contains a couple of Css and .Js files needed for the Metro Style. A manifest file is also added which defines what is needed to run the app on Windows 8.
The second project template, Fixed Layout Application, adds some basic layout to the blank application.
The Grid Application template is where things get a lot more interesting if you’re just starting writing these kinds of apps. This template contains a couple of .Html files glued together (I might dive into this in a later tutorial) with html attributes. It’s a basic starting point a grid application and contains some navigating from master to detail views.
The Navigation Applications template creates a solutions which looks a lot like the last, but blank. The basic Html elements are in place. This would be a great template to start you applications.
The last template, Split Application, create a more complex solution again. It demonstrates how to create a master/detail application showing the master and the details side by side.
Item Templates
Besides new project templates, there are new Item Templates too. Adding new files to the solution is something you would to in an Html/JavaScript application too, right? Besides a basic JavaScript File, Style Sheet or Html page, there some templates that will help you develop your Windows 8 applications faster.
The Landing Page adds a Html page, a Css file and a JavaScript file to the solution. The page contains a header with a button and a title and a section containing a list. Again, the data is defined in the JavaScript file. The JavaScript code wires thing up to create an interactive page.
The Split Page template shows a lot of resemblance with the Split Application project template. The item template adds a Html file to the solution defining the layout of the page. A Css file is added for the styling and a JavaScript file is added which contains the code to make things interactive. The JavaScript code is responsible for creating the sample data too.
The Collection Page item template defines a large item and a list of smaller items. Again a Html, Css and JavaScript file are added to the solution. It should be pretty easy to extend the JavaScript code and make the small items navigate to different pages in the solution.
The Category Page template adds a page with a horizontal list of images with some details below them. The JavaScript file that is added is pretty much the same as the ones in the previous templates and again, it should not be hard to modify and extend this code to add navigation to the page.
The Html Fragment adds an almost empty page. It contains the most basic styles and elements for a Metro style application. The JavaScript file that is added contains only a few lines of code handling the fragmentLoad event.
The Details Page contains a large text over multiple columns. The JavaScript file that goes along with this template initializes the page and fills it with sample data.
That’s it for the templates.
Wrap-up
Although this first preview of Expression Blend 5 only does Html, I think it’s moving in the right direction. Looking at the .Dll files in the root directory of Blend reassures me that the future will bring everything we’re used to back to one of my favorite tools.
Great job Expression Blend team! Keep up the good work.
For future tutorials on Expression Blend (and I’m sure many will follow) please subscribe to the rss feed or follow me on Twitter (@Sorskoot).
Customizing Silverlight properties for Visual Designers
When building custom or user controls you probably end up with a large amount of properties on that control. When using the control in a visual designer like Blend or the Visual Studio designer these properties just show up. Adding a bit of structure in this can be done very easily by adding a couple of attributes to the properties.
The attributes to let the visual design know what to do can be found in the System.ComponentModel namespace. There’s a WPF version of this namespace also.
For the sake of simplicity I’ve created a UserControl and set the background color of the LayoutRoot grid to red to be able to spot it in the designer. I’ll add properties with attributes to that control and show you what happens in Visual Studio and Expression Blend.
Categorizing
By default all properties on UserControls are grouped together in the Miscellaneous section at the bottom of the properties Panels in Blend and or in the Others section in Visual Studio.
The first property I’ve named CategoryDemo1 and it’s of type string. It doesn’t have an attribute to go with it.
When adding the control to the MainPage the properties look like this:
To add a property to an existing category add a Category Attribute to the property and give it the name of the category you would like to have you property added too.
For example, this adds the property Category2 to the Layout category:
[Category("Layout")]
public string CategoryDemo2 { get; set; }
Your property might need a category of its own. This can be done just as easily as adding to an existing category. Just use a category name that doesn’t exist yet.
[Category("CustomCategory")]
public string CategoryDemo3 { get; set; }
You might have noticed that some categories are named differently in Visual Studio and Blend, there might even be some localization used. Take for example the Common category in Visual Studio. It is called Common Properties in Expression Blend. The CategoryAttribute class contains a couple of static properties that return the CategoryAttribute for a default category. Unfortunately the static properties can’t be used when placing an attribute on a property. In part 2 of this tutorial I’ll talk about how this can be done. In the meantime you’ll have to guess a little.
The common properties category can be used like this:
[Category("Common Properties")]
public string CategoryDemo4 { get; set; }
Description
Often you might want to add a description to a property, like you would do in code. You can use the DescriptionAtrribute for this purpose.
[Category("CustomCategory")]
[Description("This is a description")]
public string DescriptionExample { get; set; }
Default Value
Often you would like to set a default value for a property. Numeric or a string or whatever. When the value is reset in the designer the property should show the default value. You can accomplish this by adding a DefaultValueAttribute to the property.
[Category("CustomCategory")]
[DefaultValue("Hello")]
public string DefaultExample { get; set; }
Hide properties
There are situations where you have properties that you do not want to expose through the UI. In cases like this you can set the BrowsableAttribute to false.
[Browsable(false)]
public string NotBrowsable { get; set; }
(intentionally left blank: can’t make a screenshot of something that’s not there)
AlternateContentProperty
The last thing I would like to show is the AlternateContentPropertyAttribute. I’m still not sure what it is used for, but it lets Expression Blend know to display the property in a different way. The property is shown in the Objects and Timeline panel. The charting controls in the Silverlight Toolkit do this too. Visual Studio doesn’t seem to do anything with this property.
[Category("CustomCategory")]
[AlternateContentProperty]
public string AlternateExample { get; set; }
Wrap up
As you can see there are various possibilities on how to display your properties in the design surfaces. But there is more. Have you ever notices the .design.dll files that came with Silverlight and the Silverlight Toolkit? I’ll continue this article in part 2 about these.
To be the first to know when it’s done, please subscribe to the RSS feed or follow me on twitter (@sorskoot).
Expression Blend Tips and Tricks at Mix11?
I was a bit surprised when I got an email from the Mix11 team congratulating me on my session proposal making the first cut. So now it’s up to the you to vote on your favorite sessions. After voting for mine, you can vote on 9 other sessions
. The entire list can be found here. The voting period ends on February 4, 2011.
My session will be focused on Expression Blend. I’ll be talking about the Visual State Manager, Sample Data and Behaviors. And I show some helpful features along way.
So go and vote now, and I hope to see you at Mix11!
Expression Blend Tips and Tricks
Learn how Expression Blend can help you when building WPF, Silverlight or WP7 applications. Find out how to use behaviors and how to build them. See how sample data can be used and created. And how you can use the visual state manager to set and animate the properties of the controls in your applications.
Using Visual States in custom controls in Silverlight
Intro
Visual States are an easy way to change the looks of your controls based on certain states. This state can be something like a mouse hover, some invalid state or any state you need in a control.
For this tutorial I chose a traffic light control that can be one of four states. Green, Orange, Red and Inconclusive (blinking orange). In the end I show you how to use behaviors on buttons to set the state of the traffic light. This makes the use of visual states perfectly suitable for use in MVVM projects.
Part 1 – Setting up the project
Start by creating a new Silverlight project in Visual Studio 2010 and add a new Item to the project by right clicking on the project in the Solution window and click Add –> New Item… or hit Ctrl+Shift+A.
Select the Silverlight Templated Control item template from the list of Silverlight templates
Add a folder named Themes to the Silverlight project. Add a ResourceDictionary to the project by using the Add->New Item… on the project folder and name this dictionary Generic.xaml. Add the following style to the dictionary:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VsmDemo="clr-namespace:VsmDemo">
<Style TargetType="VsmDemo:TrafficLight">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate/>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</ResourceDictionary>
Add a reference to the dictionary in App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/generic.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Build the solution to see I there aren’t any mistakes so far.
Part 2 – Drawing in Blend
Start Expression Blend and load the solution.
The template is still empty. To start editing the style for the TrafficLight control, go to the Resource pane, look for the generic.xaml entry, open it and click on the button on the right of the style entry.
To edit the template in the style, right click the style in the Objects and Timeline pane and select Edit Template –> Edit Current.
Now draw a traffic light like this.
If you don’t like/want/know how to draw the light, just copy-past the xaml below into the xaml editor. It’s basically just a border with a grid containing three ellipses.
<ControlTemplate>
<Border d:DesignHeight="200.00" BorderBrush="#FFCACACA"
BorderThickness="3"
Background="#FF333333" CornerRadius="40"
d:DesignWidth="110">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Ellipse x:Name="GreenLight"
Grid.Column="1" Grid.Row="1"
Fill="Black" Margin="2"
Stretch="Uniform"/>
<Ellipse x:Name="OrangeLight"
Grid.Column="1" Grid.Row="2"
Fill="Black" Margin="2"
Stretch="Uniform"/>
<Ellipse x:Name="RedLight"
Grid.Column="1" Grid.Row="3"
Fill="Black" Margin="2"
Stretch="Uniform"/>
</Grid>
</Border>
</ControlTemplate>
Instantly the traffic light should show up in the designer.
Time to save your work again. Switch back to Visual Studio, and reload the files if you’re asked to.
Part 3 – Code… Finally
The selection of the different states will be based on an enum. Add a new enum to the Silverlight project.
public enum TrafficLightStates
{
Inconclusive = 0,
Green = 1,
Orange = 2,
Red = 3
}
The state of the traffic light will be stored in the control in a dependency property. The property will be set to TrafficLightStates.Green by default. A method must be called when the property changes to notify the state manager to change the state of the traffic light.
public TrafficLightStates State
{
get { return (TrafficLightStates)GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register(
"State",
typeof(TrafficLightStates),
typeof(TrafficLight),
new PropertyMetadata(TrafficLightStates.Green,
OnLightStateChanged)
);
To get the code to build, add a basic implementation of the OnLightStateChanged method. The OnLightStateChanged method calls the non-static SetState method. This way there will be only one method in which the visual state will be changed. The SetState method is empty for now.
private static void OnLightStateChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
((TrafficLight)d).SetState();
}
private void SetState(){}
To make the four different visual states known to the application you’ll have to use the TemplateVisualState attribute. This attribute takes the name of the state and the name of the group the visual state belongs to. Add an instance of the TemplateVisualState attribute for each of the four states to the TrafficLight class.
[TemplateVisualState(Name = "Green",
GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Orange",
GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Red",
GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Inconclusive",
GroupName = "TrafficLightStates")]
Now the states are named it is time to set the visual states based on the state of the traffic light. This is done by a simple switch block in the SetState method.
Changing the visual state of a control is done though a static method on the VisualStateManager class. Calling the GotoState method with the name will change the current visual state to a new one. Any transitions will be played automatically, if the useTransitions parameter is set to true. The GotoState method also needs a control of which the visual state needs to be sit. For this example we can just pass this to the method.
private void SetState()
{
switch (State)
{
case TrafficLightStates.Green:
VisualStateManager.GoToState(this, "Green", true);
break;
case TrafficLightStates.Orange:
VisualStateManager.GoToState(this, "Orange", true);
break;
case TrafficLightStates.Red:
VisualStateManager.GoToState(this, "Red", true);
break;
default:
VisualStateManager.GoToState(this, "Inconclusive", true);
break;
}
}
The last thing that has to be done in code is setting the initial state by calling the SetState method once. You can override the OnApplyTemplate method for that.
public override void OnApplyTemplate()
{
SetState();
base.OnApplyTemplate();
}
Build to see if there are any mistakes made in the code… After that, switch back to Expression Blend.
Part 4 – Visual States
The last part of this tutorial will take place in Expression Blend. Every state of the traffic light has to have a corresponding visual state. The green light must be green, etc.
Go to the template of the TrafficLight control as shown before and open the States pane. Click on the Add State Group button on the right side of the pane.
Rename the VisualStateGroup group to TrafficLightStates.
Add four states to the group by clicking the Add state button right of the TrafficLightStates group header four times.
Rename the states to Green, Orange, Red and Inconclusive.
With the Green visual state and the GreenLight Ellipse selected, change the fill of the ellipse to green, like #FF2AFF00. Notice the red border around the drawing area indicating changes to the properties will be recorded. A small red light with a caption is shown at the top of the drawing area letting you know which state is recorded too, in this case “Green state recording is on”
This process needs to be repeated for the orange and red ellipses too. In the example I’ve used #FFFFAA00 for the orange ellipse and #FFFF0000 for the red one.
The last state, Inconclusive, needs an animation so the orange light blinks. Select the Inconclusive visual state on the States pane. Show the animation timeline by clicking on the Show Timeline button on the Objects and Timeline pane.
Move the time slider to 0,5 seconds. Change the color to Orange (#FFFFAA00). Move the time slider to 1 second and change the color to black.
Click on the first key frame and set its easing function to cubic out.
Repeat the same for the second key frame. Set its easing function to cubic out also.
Select the storyboard by clicking on Inconclusive in the Objects and Timeline pane.
In the properties pane, set the Repeat Behavior of the storyboard to Forever.
That’s it for the visual states. Try compiling the application.
Part 5 – Testing the control
Open MainPage.xaml in Expression Blend.
Add the TrafficLight control to the LayoutRoot grid and give it a width of 110 and a height of 200.
To navigate to the four different states of the traffic light, add four buttons to the LayoutRoot grid and set their content to Green, Orange, Red and Inconclusive. Like this:
To change to State property of the traffic light you can use a ChangePropertyAction. You can find this in the Behaviors group on the Assets pane.
Drag-‘n-drop this action on the first button.
Select the Action in the Objects and Timeline pane. To set the TargetObject of action to the traffic light just click on the Artboard element picker and than on the traffic light.
Select State from the PropertyName combobox.
Select Green from the Value combobox.
Repeat the same process for the other three buttons. You can clone the behavior from element to element by selecting the behavior and drag-‘n-drop it to another element while holding down the Ctrl key.
Done!
Hit F5 to admire your work
You can download the source of the project here.
If you run into any issues or if you have comments or questions, please let me know. To be the first to know if there’s a new post on my blog, please subscribe to the RSS feed or follow me (@sorskoot) on twitter.
Custom Assets folder for Expression Blend
In the projects I’m doing I often use controls from my own library or use control from third party vendors. I don’t like the process of doing this. Rather I would like to have the libraries available inside Expression Blend, like the controls that came with the Silverlight Toolkit or Blend itself.
One way is to add the custom assemblies containing the controls to one the folders in your Program Files containing the assemblies for the toolkit for example. Another and for more elegant way is to make Expression Blend look in an additional location in your UserProfile (c:/Users/SomeUser/…). The Expression Suite already has a folder in your My Documents, but not for assets.
I’ve create a .BAT file that adds a couple of folders to the Expression folder in the My Documents folder of the current user. Folders to store assemblies for .NET and Silverlight in various versions. A .REG file is used to add these locations to the windows registry.
After you have run both you’ll have to restart Blend to reread the registry and the folders. The assemblies placed in these folders are now available in Expression Blend. Your assemblies should show up in the Assets panel. By dragging and dropping them onto you pages the assemblies are automagically added to your project.
! Disclaimer: Note that by doing this you are making changes to the windows registry. Be sure to backup your system and the registry, and to save your work. I’m not taking any responsibility for you screwing up your system by not knowing what you are doing. Using the .reg and .bat files is at your on risk.
Gradient Importer for Expression Blend
Intro
Adobe Photoshop offers people the possibility to share gradients through .GRD files. These files can be found very easily on various sites. This extension for Expression Blend allows you to import these files and use them in your Silverlight or WPF projects.
The extension makes use of some changes to Expression Blend made in SP1. You must have Blend SP1 installed to use this extension.
Know limitations
The extension isn’t finished yet. I haven’t worked out all the bugs yet, but this first release should enable you to import most of the .GRD files.
In Adobe Photoshop it is possible to create a noise gradient type. This type of gradient isn’t available in Xaml. At this point the extension will show an error when a file containing a noise gradient is opened. In a future version the noise gradient will be skipped.
Because there is no documentation on how to interact with Expression Blend from extensions I have not been able to create a new resource entry from code. I’m not even sure if this is possible at all. Therefore I have chosen to show the Xaml created from the imported gradient and give you the opportunity to copy the Xaml to the clipboard. This way you can place it wherever you want.
I have tested the extension with various .GRD files, but it is possible you may encounter files that do not import and generate errors. Please take the time to inform me about these and send me an email with the .GRD file or a link to it.
Installation
You can download the extension here. All you have to do is extract the file in a temporary directory and copy the .DLL into the extensions folder of Expression Blend 4. If you have the FXG importer installed that came with SP1 this folder should already be there. If not, just add it to Expression Blend folder and Blend knows what to do with it.
Using the extension
After the .DLL file of the extension is placed in the /extensions folder you should restart Expression Blend. Open the solution you want to add the imported gradient to.
Go to the File menu and choose the newly added menu item “Import gradient file…” .
An dialog window should pop up. Click on the “Load .GRD” button in to top right corner. The should bring up a file dialog. Browse to the .GRD file, select it and click “Open”.
The file is opened and its contents are shown in the list box. Select the gradient you would like to add to your project and click “Import”.
A new dialog window containing the Xaml for this gradient. You can alter the Xaml if needed.
Click on the “Copy to Clipboard” button to copy the Xaml to the clipboard.
After this you can close the window and paste the Xaml into the resource location of your choice.
What to expect next
I have planned to work on blog post about the inner workings of this extension. Mainly focused on how it works inside Expression Blend. If you run into any issues, have comments or if you have feature requests, please let me know by adding a comment to this post or by sending me an email.

The first part of the session I explained Sample Data. I demonstrated how to create it and how to use it to create bindings. I demonstrated how to use the Visual State manager and set them by using behaviors. In the last demo I showed a couple of my favorite features of Expression Blend (including the gradient picker).
