Expression Blend

Extending Blend for Visual Studio

Once upon a time, in a galaxy far away, I wrote a couple of tutorials on how to write extensions for Expression Blend. Today there’s still not much information available on how to write your own extensions. But it is still possible to extend Blend for Visual Studio. The way to do this is slightly changed though.

I recently came across a question at StackOverflow.com that made me decide to update/rewrite some that older tutorials.

Instead of building some dummy extension I’d like to show you how to build an extensions that might be useful for developers of Windows Store apps and Windows Phone apps. The extension is going to display a list of characters of the Segoe UI Symbols font you can use in you apps.

Getting Started

To be able to build directly into the extensions folder of Blend and have Visual Studio debug them you’ll have to start Visual Studio as administrator.

When Visual Studio is started create a new WPF User Control Library project. This will add the necessary references for creating a user control that will be our panel in Blend.

I named the extension SegoeSymbol, but feel free to use anything you like…

image

Next we’ll have to change some of the configurations of the project to have Blend pick the extension right from it’s extensions folder.

Go to the properties of the the project and change the Assembly Name on the Application tab to “SegoeSymbol.Extension” . This will name the assembly SegoeSymbol.Extension.dll. All extensions need to have the .extension.dll suffix.

Also change the Target framework to .NET Framework 4.5.

SNAGHTML29561b27

Set the Output Path on the Build tab to “c:\Program Files (x86)\Microsoft Visual Studio 11.0\Blend\Extensions\” . If you have installed Visual Studio 2012 in any other location this path might be different. Also, make sure the Extensions folder exists.

SNAGHTML29705c9a

The last property to changes is the Start Action on the Debug tab. Set this to the full path to “Blend.exe”. This way Visuals Studio will start Blend when you hit F5 and attaches the debugger to the process enabling you to set breakpoints and such.

SNAGHTML29737355

Code

Before we can do anything with this extension we need some code. The project we just created doesn’t have a class file yet, so we’ll have to add a one. Name it SegoeSymbol. This class will be the entry point for the extension.

This class has to implement the IPackage interface from Blend. To get this interface you’ll have to reference Microsoft.Expression.Extensibility.dll. You can this assembly in the root folder of Blend, the same folder you’ve found Blend.exe in a bit earlier.

Implementing this interface will give you two methods, Load and Unload. The Load method is called when Blend loads the extension. And, you might have guessed, Unload is called when Blend unloads the extension. Blend will load the the extension when it is started and unload the extension when it is shut down.

Blend for Visual Studio uses the Managed Extensibility Framework, or MEF, to load extensions. MEF is included in the .NET framework. All you have to do is find the reference to System.ComponentModel.Composition. MEF works by decorating a class you want to enable as extensions with the Export attribute and providing that with the type you’d like to export. The other side, Blend in this case, is using an Import based on the IPackage interface to get to the extension. By now your code should look something like this:

namespace SegoeSymbol
{
    using System.ComponentModel.Composition;
    using Microsoft.Expression.Extensibility;

    [Export(typeof (IPackage))]
    public class SegoeSymbol : IPackage
    {
        public void Load(IServices services)
        {
        }

        public void Unload()
        {
        }
    }
}

One last thing before you build and run your code. By default all assemblies referenced that are not in the GAC are copied to the output directory. Because Blend has everything you need, you can set the Copy Local property of all references to False. If you need to have a reference included with your extensions you can leave that one to true.

SNAGHTML2a8e3689

If you like you can try it out now… If you place breakpoints at the opening brackets of both methods you will see them both hit when opening and closing Blend.

A small thing you might run into when developing extensions is that Blend will lock the extension assemblies when it has them in use. This means you can’t have Visual Studio compile and build you extensions when Blend is running. Even to the point where if you close Blend a process, Microsoft Visual Studio XAML UI Designer (32 bit), will keep the files locked. I have to look a bit more into why and when this process is used. But you often have to go into the process explorer and end the task by hand. If you hit the “stop” button in Visual Studio it will kill Blend most of the time, which unlocks the files. I don’t know if this is a bug or a feature.

I’ll get back to this class in a second. First we should have a look at the…

User Interface

An extension needs a user interface, right? The user interface doesn’t do anything with Blend itself or with the extension so I’ll go over it rather quickly.

Because we started with the WPF User Control Library template we already have one. I renamed this to CharacterSelector.

Lets have a look at the XAML part of the UI. It’s basically just a ListBox with some styling. I changed the ItemsPanelTemplate (on line 27) to contain a WrapPanel instead of a StackPanel so all icons will be placed next to each other until a row is full at which point it will wrap to the next row.

The ItemTemplate, defined on line 14, draw a border around a TextBlock that contains the character in the Segoe UI Symbol font.

The whole thing is combined in a ListBox, line 34. The selection changed event is handled in the code behind.

<UserControl x:Class="SegoeSymbol.CharacterSelector"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300"
             d:DesignWidth="322.667"
             Width="Auto"
             Height="Auto"
             MinWidth="325">
    <UserControl.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="ItemTemplate">
                <Border BorderThickness="1"
                        Width="50"
                        Height="50"
                        BorderBrush="White">
                    <Grid HorizontalAlignment="Center"
                          VerticalAlignment="Center">
                        <TextBlock Text="{Binding Character}"
                                   FontFamily="Segoe UI Symbol"
                                   FontSize="24" />
                    </Grid>
                </Border>
            </DataTemplate>
            <ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
                <WrapPanel />
            </ItemsPanelTemplate>
        </ResourceDictionary>
    </UserControl.Resources>

    <Grid>
        <ListBox x:Name="listBox"
                 Background="{x:Null}"
                 ItemTemplate="{DynamicResource ItemTemplate}"
                 ItemsPanel="{DynamicResource ItemsPanelTemplate1}"
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                 ScrollViewer.VerticalScrollBarVisibility="Auto"
                 SelectionChanged="listBox_SelectionChanged" />
    </Grid>
</UserControl>

In the code behind I fill the selection with characters and handle the selection. The list of characters is created with a simple for loop at line 16. This loop instantiates a helper class MetroIcon (see line 57) and fills it with a number and the corresponding character. After the loop the collection of characters is assigned to the ItemsSource of the ListBox (line 27).

When an element of the ListBox is selected, when the extension is running in Blend, the Listbox_SelectionChanged event handler is called (line 27). To keep things simple, the character selected is copied to the Windows clipboard. As text, but formatted in a way xaml-text can handle it.

Here’s the code:

namespace SegoeSymbol
{
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    ///     Interaction logic for CharacterSelector.xaml
    /// </summary>
    public partial class CharacterSelector : UserControl
    {
        public List<MetroIcon> Collection = new List<MetroIcon>();
        public CharacterSelector()
        {
            Collection = new List<MetroIcon>();
            for (int i = 0xE100; i < 0xE271; i++)
            {

                Collection.Add(new MetroIcon()
                    {
                        Character = ((char)(i)).ToString(),
                        Value = i
                    });
            }

            InitializeComponent();
            listBox.ItemsSource = Collection;
        }

        /// <summary>
        /// Handles the SelectionChanged event of the listBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance 
        /// containing the event data.
        /// </param>
        private void listBox_SelectionChanged(object sender, 
                                              SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count>0)
            {
                var metroIcon = e.AddedItems[0] as MetroIcon;
                if (metroIcon != null)
                {
                    string val = string.Format("&#x{0:X};", metroIcon.Value);
                    Clipboard.SetData(DataFormats.Text,val);
                }
                listBox.SelectedItem = null;
            }

        }
    }

    /// <summary>
    /// Data class for holding Character and value
    /// </summary>
    public class MetroIcon
    {
        public string Character { get; set; }
        public int Value { get; set; }
    }
}

Lets have a look at gluing the whole thing together.

Adding the control to Blend

We’re going to make some magic happen in the Load method created earlier in this tutorial. Blend calls the load method and passes it its IServices implementation. You can use this class to get access to various services that Blend exposes. One useful service is the IWindowService. This service is responsible for the panels you see all around Blend. To be able to use the IWindowService interface you need reference Microsoft.Expression.Framework.dll and make sure you set “Copy Local” on false.

To get access to IWindowService you need to call the GetService method on services that was passed as a parameter. When you give this generic method the type IWindowService, it will return an instance of that type that Blend is using.

Next, create an instance of the CharacterSelector control we created in the previous chapter. If you someday need IServices in a user control, just extend the constructor and pass it in.

The last thing to do is register the control as a “Palette”. Palettes are the panels in Blend. To register a new palette call the RegisterPalette method on windowService and give it an identifier, the instance of the control and a title. You can provide a fourth, optional, parameter to set some extended properties on the palette, but we’ll use the defaults for now.

The Load methods should be looking something like this by now:

public void Load(IServices services)
{
    IWindowService windowService = services.GetService<IWindowService>();
    CharacterSelector characterSelector = new CharacterSelector();
    windowService.RegisterPalette("SegoeSymbolExtionsion",
                                  characterSelector, 
                                  "SegoeSymbol");
}

At this point you should be able to hit F5 and find the extension in Blend.

After Blend is started you need to create or open a project. If you look in the Window menu, the palette is shown right there.

SNAGHTML979ba99

When the SegoeSymbol panel is visible it behaves like all other panels in Blend. In this case it is docked next to the Resources panel.

SNAGHTML978ee17

What’s next?

I think we’ve got the basics down at this point. There are a lot more things you can do, like creating menus and commands or using documents and dialogs.

Please note that anything you just read is based on my own findings. There is no documentation available on writing these extension, no support and no guarantee it will even work in a next version of Blend for Visual Studio.

setting view states in HTML windows store apps using Blend

Intro

From developing XAML applications I got used to working with the visual state manager to set various states of my applications and controls. In Windows Store apps that are build using XAML use the visual state manager to change various properties when the view state of the app changes. The app can be ran in fullscreen, filled or snapped state.

When building Windows Store apps using HTML and JavaScript I wanted to show some UI different when the view state changes. One way to accomplish this is to change the CSS class of the elements from JavaScript. Just handle the change in view states and call some methods to set the classes.

Another way comes very close to the visual state manager from the XAML world. And can be done from within Blend.

CSS Media queries

It turns out you can set the styles for the view states using CSS media queries or media types. You might know these from building websites, where they’re often used to set different styles for different media or screen sizes.

If you look at the Style Rules pane in Blend for Visual Studio, when having an HTML Windows Store app opened, you can see four different “@media” definitions. Each one is used for a different view states. The media queries are added by default, but if they are missing or you want to add another you can do this by right click on the .css file.

image

Notice that only the fullscreen-landscape is white. The other three are greyed out. This is an indication that Blend is showing the landscape orientation at this moment. You can change the current orientation used in Blend on the Device pane. Just select another option for view.

image

To demonstrate how to use this I created a very simple example showing a grid with 6 boxes. For this I used a FlexBox. When a FlexBox is filled with elements they are stacked horizontally or vertically and wrapping could be enabled.

image

html:

<div class="ms-flexbox">
    <div class="tile red"></div>
    <div class="tile green"></div>
    <div class="tile red"></div>
    <div class="tile green"></div>
    <div class="tile red"></div>
    <div class="tile green"></div>
</div>

css:

.ms-flexbox {
    display: -ms-flexbox;
    -ms-flex-flow: wrap column;
    width: 1000px;
}
.tile {
    width: 250px;
    height: 200px;
    margin: 20px;
}
.tile.red {
    background-color:red;
}
.tile.green {
    background-color:green;
}

A similar layout like this is often used in Windows Store apps. Unfortunately it does not work when the app is snapped. In the snapped state the elements should be shown in a list, but will remain in three columns at this point. You’ll need to place parts of the .ms-flexbox class in both @media queries. You could do this by hand by editing the .css file, but I’ll show you how to do it using Blend.

The first step is to copy the .ms-flexbox class to the fullscreen-landscape and to the snapped media queries. Just right-click the .ms-flexbox entry on the Style Rules pane and click copy. That paste it on the fullscreen-landscape and the snapped media queries.

image

image


 

 

Next, select the original .ms-flexbox class and have a look at the CSS Properties pane. There’s a long list of collapsible panels containing a lot of properties. To shorten the list to only the properties that have a value, check the “View set properties only” checkbox. 

image

The original .ms-flexbox style will be the style that is applied to all view states and contains the properties that are equal in every state. The Flexbox properties will be different. So these need to be removed. To do this click on the small advanced properties square next to Flexbox and select clear.

image

Select the .ms-flexbox style on the fullscreen media query on the Style Rules pane. For this part of the style clear the layout and the sizing. And do the same for the style on the snapped media query.

The style for the snapped state has to have some different properties for the Flexbox. Start by setting the View to the snapped state on the Device pane, so it visible what the change in properties is causing. First, clear the –ms-flex-wrap property, because in this state wrapping is not needed. Than, set the
–ms-flex-direction property to column. Notice the change in the designer.

image

And that’s it. Well… Almost actually. We haven’t done anything with the filled and fullscreen-portrait states. You could copy the state from the landscape state, but this would mean you’ll have to keep them in sync in case of changes.

At this point I changed the CSS by hand and added the filled and portrait definition to the landscape view state, which results to:

@media screen and (-ms-view-state: fullscreen-landscape),
screen and (-ms-view-state: fullscreen-portrait),
screen and (-ms-view-state: filled)
{
    .ms-flexbox {
        -ms-flex-flow: wrap;
    }
}

Wrap up

Handling view states is an important part of you Windows Store app. In a real world application the styles and HTML will be a lot more complex than I showed here, but I hope you’ll get the idea. Otherwise, just drop me a line and I’ll see if I can expand the tutorial.

Wp7nl utilities Contribution

When building apps for Windows Phone I use my own library. I’m a “lazy” developer and don’t like writing code twice. So I place a lot of code that can be reused, like behaviors, converters and extension methods, in my library. For I while I’ve been thinking about sharing the library as an open source project on Codeplex, but in the end decided to contribute to the Wp7nl Utilities project of Joost van Schaik. The first bunch of utilities are added. I will continue to add more and describe those on my blog too.

Actions for Launchers

behaviorsI often have simple trigger actions that need to be executed in my apps. For example, opening a URL in Internet Explorer or sending an email. Because I use Blend a lot (and I’m lazy ;) ), I just like to drag and drop an action to a button or text block and be done with it. The great thing about actions and behaviors is that you can bind the the properties which makes them very useful in templates.

At this point only a few of the possible Windows Phone Launchers are available as trigger actions, but I’m sure the list will grow over time. If you would like one added just let me know and I’ll see what I can do.

NavigateToUrlAction

Using these actions is very simple. The code surrounding the action is pretty much the same for all actions, only the event name might change. The NavigateToUrlAction performs a WebBrowserTask. It opens up the Url property so you can bind to it. As a small extra feature it checks if a network connection is available and shows a message if there isn’t. This message can be customized as well.

<Button Content="Wp7nl" HorizontalAlignment="Left" VerticalAlignment="Top">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Tap">
            <behaviors:NavigateToUrlAction Url="http://wp7nl.codeplex.com"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

SendEmailAction

This action executes the EmailComposeTask. The “To”, “Subject” and “Body” properties can be bound to.

 

NavigatieToMarketplaceDetailAction

This action executes the MarketPlaceDetailTask. It opens up the marketplace and shows the details of your app.

 

NavigatieToReviewAction

Getting people to review your apps is crucial for a successful app. This action executes the MarketplaceReviewTask and makes it very easy for users to review.

 

ShareLinkAction

Sharing links is a very common task in apps. This action executes the ShareLinkTask. So you can use the native sharing features of the phone. The “LinkUri”, “Message” and “Title” properties can be bound to.

 

Limit TextBox Behavior

I ran into cases where I wanted to limit the number of characters a user can enter. This behavior an only be used with a TextBox element. You can set the maximum number characters that can be entered in the “MaxChars” property. As a bonus feature you can have the phone vibrate a little when the maximum number of characters is reached.

<TextBox x:Name="LimitedTextbox">
    <i:Interaction.Behaviors>
        <behaviors:LimitTextBoxBehavior MaxChars="25" Vibrate="True"/>
    </i:Interaction.Behaviors>
</TextBox>

Visible On Locale Behavior
The VisibleOnLocaleBehavior sets the attached element to visible if the current UI language of the phone matches the specified two letter ISO language name and hides it when it doesn’t. The behavior can be used I you have certain element, like images, that are language specific.

<TextBlock Text="English" >
    <i:Interaction.Behaviors>
        <behaviors:VisibleOnLocaleBehavior LanguageCode="en"/>
    </i:Interaction.Behaviors>
</TextBlock>
<TextBlock Text="Nederlands">
    <i:Interaction.Behaviors>
        <behaviors:VisibleOnLocaleBehavior LanguageCode="nl"/>
    </i:Interaction.Behaviors>
</TextBlock>

Visibility In Trial Behavior
The VisibilityInTrialBehavior sets the attached element to visible or collapsed if the app is in trial mode. Whether the attached element should be visible or collapsed is determined by the “Visibility” property.

<TextBlock Text="Not in trial mode">
    <i:Interaction.Behaviors>
        <behaviors:VisibilityInTrialBehavior Visibility="Collapsed"/>
    </i:Interaction.Behaviors>
</TextBlock>

This behavior makes use of the TrialHelper. This helper is used to see if your app is running in trial mode. The be able to run your application in trial mode you can add “TRIAL” as a conditional compilation symbol to fake it when debugging.

image

Converters

I’ve added a couple of converters to the Wp7nl library. Most of which are very simple.

ObjectToStringValueConverter

Let’s start with the one that needs the most explanation. The ObjectToStringConverter is used to create a nicer representation of an object. Add properties of the bound object between { } to the converter parameters.

Take, for example a Person class.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Whenever you would like to have a textblock show the last name and the first name separated with a comma, you could just add that to the converter parameter.

For this example I’ve set the datacontext of the mainpage to a new instance of the person class directly in the constructor. You wouldn’t do that in a real application of course, but you’ll get the idea.

public MainPage()
{
    InitializeComponent();
    DataContext = new Person{FirstName = "Larry", LastName = "Laffer"};
}

Than I’ve added a databinding to the textblock.

<TextBlock Text="{Binding ConverterParameter=\{LastName\}\, \{FirstName\}, Converter={StaticResource ObjectToStringValueConverter}}"/>

When creating the binding in Blend, you don’t have to escape the curly brackets, as shown in the image below.

image

NullToCollapsedConverter

Returns Visibility.Collapsed for any value that is null, empty, only whitespaces or an empty guid. Very useful to hide empty stuff. You don’t want to show a navigate to URL button if the URL is empty, for example.

 

StripHtmlValueConverter

Removes all HTML from a string and decodes ‘&XXXX’ to regular chars. Often when data is requested from external services like Twitter or Facebook, it contains HTML at some point. This HTML has to be converter to either a regular string or to some sort of rich text block. This converter does the first, removing all HTML. <BR /> tags are changed to new lines.

 

ToLowerValueConverter

Converts a string to all lowercase characters. Useful for headers.

 

ToUpperValueConverter

Converts a string to all uppercase characters. Useful for titles.

Customized Sample data

Intro

When working on Windows Phone or Silverlight applications I use the sample data feature of Blend a lot. I like to see what I’m working on. The only downside of this sample data is that it rarely mirrors the data (unless I’m working on the chair application for a company called Lorem Ipsum). I’d like to see Dutch phone numbers, cities and postal codes. So I’ve decided to create my own list of sample data. At first I thought I had to build a new extension for Blend to be able to customize the data. It turned out to be far less complicated.

imageHow?

The “String” type of sample data is stored in two files. If you’ve installed Blend on the default location you can find these files at:

  • Blend for Visual Studio ==> C:\Program Files (x86)\Microsoft Visual Studio 11.0\Blend\SampleDataResources\en\Data
  • Expression Blend 4 ==> C:\Program Files (x86)\Microsoft Expression\Blend 4\SampleDataResources\en\Data

 

The first file, LoremIpsum.txt, contains a dummy text. This text is loosely based on Latin an is commonly used as dummy text. The second file, SampleStrings.csv, is a comma delimited file that contains the names and words you are probably used to when working with sample data. All you need to do if you want to create custom data is replacing these files.

Because I’m Dutch and would like to use Dutch dummy text I replaced the contents of the LoremIpsum.txt file with some of the generated text on this page. This immediately makes the random generated text look Dutch.

Replacing the SampleStrings.csv file was a bit more complicated. I assumed the strings had to be in the exact same format as they were, but I was wrong here. You can do whatever you want with this file, as long as the first row of elements are the names of the data you are fine. These names show up in the Format combobox.

Besides the obvious things like first name, last name and addresses, I added a few thing I always needed as sample data but didn’t have. I added image urls and a thumbnails that point to http://lorempixel.com. That way I have “real” images when binding the sample data to the source property of an image. I also added dummy tweets. These are just texts but sometimes start with @ or RE, can contain a url or sometimes have a random hash tag.

Download

You can find both files in SampleData. I also include .bak files of the original files.

image

WinJs DesignTime Mode

While working on the port of my game Orbizoid to Windows 8 I ran into an issue with the starfield in de background of the game. The starfield was running in Expression Blend too. At first this was kinda funny, but soon the performance dropped and it became unworkable. There used to be a property to detect if you are running inside Expression Blend before, I hoped this was still available when working on Windows 8 applications in javascript. I had to search for a moment, but it is possible.

var isInDesigner = Windows.ApplicationModel.DesignMode.designModeEnabled;

if(!isInDesigner){
// code not running in Expression Blend
}

now you can safely use the isInDesigner variable throughout your code to enable/disable specific code running in Blend.

Getting started with Metro, JS and blend

Intro

In this first tutorial in a series about building a Windows 8 application with JavaScript, HMTL and CSS using Expression Blend 5, we’re going to make a start on a very simple game. In this game the player has to guess a random number between 1 and 10. The player wins if the guess is correct, and looses if it’s wrong. In future parts of the series this game will be extended to include various features of WinJS and Windows 8.

File-New

I’ve started with a new “Blank App” from the HTML list. I added a few HTML elements to start from. You can add HTML elements by typing them in the source panel. Or you can drag’n’drop them from Assets pane to Live DOM pane or design area.

File-New

I’ve added the following to the body-tag. Don’t worry about the looks of it, we’ll fix that later.

<h1>Guess a number</h1>
<p>
    <span>Enter a number between 1 and 10:</span>
</p>
<p>
    <input />
    <button>Guess</button>
</p>
<p>
    <span>result:</span>
    <span></span>
</p>

 

The easiest way to access the HTML elements is by assigning IDs. I assigned the following IDs:

  • input ==> numberInput
  • button ==> numberGuess
  • the empty span ==> numberResult

That’s it for the HTML for this moment. Let’s have a look at some code.

Code

Although Expression Blend is an awesome tool, I still prefer to edit my code in Visual Studio. Right click the default.js file and select Edit in Visual Studio to do just that.

image

For now we’re going to ignore most of the code that’s inside default.js. It’s almost all about state management. We’ll talk about that in a later tutorial. I’ve added the following code right below WinJS.strictProcessing(); :

var randomNubmer = Math.round(Math.random() * 10) + 1;

function buttonClickHandler() {
    var value = document.getElementById("numberInput").value;
    var numberResult = document.getElementById("numberResult");
    if(value == randomNumber) {
        numberResult.textContent = "Correct";
    }else {
        numberResult.textContent = "Incorrect";
    }
}

Line 1 of this piece of code generates a random number and makes sure it’s between 1 and 10.

From line 3 and further the click event handler is defined. The first thing this function does is reading the value from the input with the numberInput id. Than, the element for the result is stored. The last thing this function does is comparing the provided value with the random number. If they are equal the text on the result is set to Correct, otherwise it’s set to Incorrect.

The event handler has to be attached to the button. This can be done in the following way:

var numberGuess = document.getElementById("numberGuess");
numberGuess.addEventListener("click", buttonClickHandler, false);

These lines need to be placed after the call to args.setPromise(WinJS.UI.processAll());.

It takes the element with the numberGuess id, and adds an event listener to that. The event handler is told that it should handle the click event and that it should handle the click event with the buttonClickHandler function. The last parameter tells the event listener that it should use bubbling. This means that the event will bubble up the hierarchy of DOM elements and is handled by each element before calling a possible event handler on its parent. Bubbling is what you would want most of the time. The other option, True, means the event listener needs to use capturing. This means the event is handled by the parent first and than the child.

With this piece of code in place it is time to run the application to see if it works. You can hit F5 in Visual Studio or Expression Blend to run the application. Or you can use the interactive mode in Expression Blend.

image

The great thing with this is that you can bring your application is a specific state and continue editing from there.

CSS

If everything’s right you should be able to play the little game now. Time to make it look a little better by adding some CSS styling.

There are a couple of ways to set the CSS properties for the application. You can set them directly on the objects. To give the elements we added in the beginning a bit more space around the border we’re going to change the padding on the body tag. First, select the body element in the Live DOM pane. Now, go to the CSS Properties pane and look in the Layout section.

image

To set the padding for all borders at once make sure the link option, right next to the inputs, is set. Enter 50px in the first input box and note that all boxes are filled with the same value. The CSS properties are stored in the HTML in the style attribute, in this case on the body tag.

To demonstrate a second way of setting styles we’re going to make the title look glowing, bold and blue. We’re going to add a CSS style rule to store the properties. To do that select the title in the designer, right click on it and select Add New Class…

image

The class has to have a name. Enter title in the input box. Because we want the properties to be stored in a CSS style rule make sure the Create style rule checkbox is checked. Hit OK.

image

The title style rule is automatically selected. Go to the CSS properties pane and look at the top section.

image

As you can see the .title rule is selected and that it is stored in the default.css file. The rules below the .title are default rules which are stored in the ui-dark.css file. Because there are different ways in which CSS properties can be set and because they can be overwritten by others all origins of properties are listed here. Each row is loaded on top of the one below. To two options above the line are special. If you select Winning Properties the CSS Properties pane shows a flattened view of all set properties. Very useful to see what values are set. You can even see where a value came from by clicking on the little advanced properties peg next to a set property. In the CSS Cascade section is shown what caused the value to be the way it is.

The computed values option shows a read-only view of all values. Even the ones that are not set.

Right. To make the title look blue select the .title element in the Applied Style Rules list. Go to the Text section. Set the color to light blue, the font-weight to 400 and enter 0 0 5px #4488FF in the text-shadow box. This gives the text a glow look by adding a shadow without X or Y offset.

image

A nice thing to notices is the way Expression Blend tells you were a specific style rule is used. Now that we have the .title rule set, go to the Style Rule pane and select it. At this point the Live DOM pane should have the H1 element highlighted with a dark green background. In the designer the title has a green border. If there would be multiple elements with the selected style rule, all of them would be highlighted in the same way.

image

For the last way of setting the styling I would like to show you we have the add a little code first. In the click event handler, in the check if the number is correct I’ve added two lines. These lines set the CSS class to correct or incorrect based on the result.

if(value == randomNumber) {
        numberResult.textContent = "Correct";
        numberResult.setAttribute("class", "correct");
}else {
    numberResult.textContent = "Incorrect";
    numberResult.setAttribute("class", "incorrect");
}

Switch back to Blend and enter interactive mode. Type a number in the textbox and hit Guess. You’ll probably hit an incorrect number, but for the tutorial it doesn’t matter very much. The .incorrect rule should make the text turn red and the .correct rule should make the text turn green. After having the result shown leave the interactive mode and select the numberResult element. Go to the HTML Attributes pane.

image

A couple of thing are happening here. The first thing to notice are the blue borders around the class box and the textContent property. This blue border means these values are set at runtime. The little lightning bolt next to the class name also indicates this class has been added at runtime.

To convert the dynamically added class to a normal style rule, click on the advanced properties peg, go to Create Style Rule from Element Class and select incorrect.

image

Go to the Style Rules pane, which should contain the .incorrect rule now. Select it and go to the CSS Properties pane. Set the color to red. You can repeat the process until you guess the number, or you can add the .correct rule by clicking the + on the Style Rules pane. Select the rule and set the text color to green.

image

Wrap-up

This first tutorial in the series turned out to be a little longer than I suspected, but I hope you get the basic idea of setting the styles of your apps. If you have any questions just let me know. You can download the code for this tutorial here.

Styling Windows Phone 7 Pivot Control Titles

For a Windows Phone 7 application I’m currently working on I needed to change the font the titles of a couple of PivotItems on a Pivot control. Normally I won’t recommend using another font than Segoe WP for this, but sometimes the branding of the app leaves you no other choice.

Changing the font of the title turned out to be a lot harder than I thought. To spare you the trouble, here’s how it’s done in Expression Blend.

Walkthrough

For this walkthrough I created a very cool app, containing a Pivot control with three PivotItems.

image

Changing the font of the title of the Pivot itself is easy. With the Pivot selected in the Objects and Timeline pane set the font property to whatever you need.

imageimage

Setting the same font for the titles of the PivotItems is a bit more complex. With the Pivot control still selected, click on the Pivot(just below the tabbar above the design area) and follow Edit Template –> Edit a Copy…

image

The Create Style Resource dialog appears. You could name the style here and place it a Resource Dictionary if you like. For now, just hit OK.

image

You’ll end up with the inner components of the Pivot.

image

Select the HeaderListElement from the Objects and Timeline pane. This is the bar that contains the titles of the PivotItems. And go to HeaderListElement –> Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy

image

I probably should give my style a cool hip name, but for the demo I’ll just leave that up to you and hit OK right away…

image

We have reached our final destination, the template that holds the properties for the title of the PivotItem.

To set the font of the titles you need to do a little trick. Because the ContentPresenter doesn’t have a font property you need to change it to something else, preferably another control that can contain content. So, change the xaml of template and turn the ContentPresenter into a ContentControl.

image

The ContentControl has the needed text properties. I’ve set the font to the one I needed and changed the font size to 70pt. A small side note: make sure you embed the font in your app, otherwise it won’t work when the app is running in the emulator or on the phone.

image

As you might have notices, the color of the titles is grey and white. Which isn’t very cool. So the last part of this tutorial will show how to change that.

Have a look at the visual states on the State pane and notice there are two states. Selected and Unselected.

Select the Selected state and notice the red border around the design area indicating every property you change will be recorded into this visual state. You can use resources in your visual states. Which is handy when you want to use the phone’s accent color. Make sure the element named "ContentPresenter” is selected in the Objects and Timeline pane and select the foreground color brush. Select the Color resources tab and set the color to the PhoneAccentColor.

image

To show a bit of what the visual states can do, and have a little bit of fun with the Pivot control too, we’re going to make the selected state slightly bigger than the unselected state. With the Selected state and the “ContentPresenter” element still selected change the scale of the RenderTransform to 1,1 for both the X and Y scale.

image

To make the scaling a bit more noticeable when the app is running. I’m going to set the transition between states to 0.5 seconds, with a CubicInOut easing.

image

And that’s is. You’ve changed the title of the items in a Pivot control.

colorizing images using expression blend

Yesterday I recorded a screencast to demonstrate how to colorize images in a Windows Phone 7 application using Expression Blend 4. In Silverlight or WPF I use a shader to colorize images, but because shaders aren’t available in the same way in Silverlight for Windows Phone I had do come up with a different technique. In this tutorial I show how to use application bar icons as an opacity mask on rectangles. I set the fill brush of these rectangles to the default phone accent brush.

Here’s the video:

colorizing images using expression blend

What’s new in Expression Blend for visual studio?

Intro

With the release of Windows 8 Customer Preview came the release Visual Studio 11 Beta. This beta release van with a new version of Expression Blend. To get it, just download the Visual Studio 11 Beta and install the Ultimate, Premium of Professional version. If you don’t have installed or don’t want to install Windows 8, you can install Visual Studio on Windows 7 now. It runs side by side with any previous installation of that.

There is one downside of running the Beta on Windows 7: you can’t develop WinRT applications. The file->new Project windows is even completely empty in this release. But that doesn’t mean you can’t work on Silverlight projects. You’ll just have to create them with Visual Studio for now, and than open them in Blend.

Unfortunately Windows Phone or WPF development seems not to be possible with this release, but please correct me if I’m wrong…

I’ve made a small list of changes when using Expression Blend for Visual Studio on Windows 7 when working on Silverlight projects.

Changes

imageThe first thing to notice when Blend is started are the changed icons, they’re a bit smaller too. They’re styled in the same way as the icons in Visual Studio 11.

The toolbar has only a few minor changes. The basics are the same, but there are a few controls that are removed or added to it.

The various panes look pretty much the same as in previous version of blend. There are a few rounded ‘corners’ removed. The changes are very minor, but somehow the UI feels different.

 

 

 

 

 

A new feature is the possibility to change the sorting of the properties in ‘Properties’ pane. You can now arrange them by ‘Category’, ‘Name’ or ‘Source’. If you’re used to “designing” ;) XAML applications in Visual Studio 2010 this feature might be familiar. Category is what was the way Expression Blend used to sort the properties and still is the default. Arranging by Name does what it says, sorting by name. The last option is also very useful. Arranging by Source groups properties that have their value set together, which makes it very easy to find these. image

One other small change is that ‘View XAML’  is renamed to ‘View Code’ in various context menus.

image

A similar feature is added to the ‘advanced-options-peg’, the little square behind the properties. You can now jump directly to the XAML to where the value is defined.

image

At some point I noticed one of the pegs to be blue, instead of white, green or yellow. The tooltip revealed it was set with an ‘ambient’ value. You can’t do anything with it at this point, but I assume it indicates the value is set by some other resource. In this case by the Style.

image

Editing of grids is changed a little to. It has become a lot easier to add, move and changes columns and row of a grid. Just hover and click in the designer to change the settings of the column or row. When moving rows or columns around, the contents move along…

image

Wrap up

Well, that’s about that at this point. There aren’t that many changes in the Silverlight scenario, but at least there’s some improvement. A couple of features came over from visuals studio, a couple are entirely new. I guess most of the new features are focused at Metro and running Expression Blend on Windows 8. Let’s hope improvement will continue and more features will become available with future releases…

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.

Logo-WhiteLogo-Black

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:

image

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

image

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.

image

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

image

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.

Twitter