Expression Blend

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…” .

image

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”.

image

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”.

image

A new dialog window containing the Xaml for this gradient. You can alter the Xaml if needed.

image

Click on the “Copy to Clipboard” button to copy the Xaml to the clipboard.

image

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.

 

-={ Download Extension }=-

-={ Example Gradient }=-

XamlResource.com

Since today XamlResource.com is officially in beta. Its purpose is to create a platform to find and share resources for Silverlight and WPF, resources in the form of Xaml. Have a look around and if you run into issues, please let us know at xaml@hotmail.nl.

 

Beta 1:

In Beta 1 only a few of the final categories are supported:

  • Colors; Resources of type SolidColorBrush
  • Gradients; Resources of type GradientBrush
  • Color sets; 2 to 5 resources of type SolidColorBrush
  • Vectors; Resources of type StreamGeometry

This list will be extended with Styles, Themes, Templates and Shaders.

 

Future plans:

  • Adding tags and searching by them.
  • Access to the site from within Expression Blend
  • Client side validation of entered xaml using Silverlight
  • Automatic generation of preview image
  • Download multiple resources at once in one ResourceDictionary
  • An rss feed for news items

If you have requests for features you can let them know by using http://XamlResource.uservoice.com. For anything else, send an email to xaml@hotmail.nl.

To keep up to date, follow us at http://twitter.com/XamlResource

 

Logo

MVVM Project and Item Templates

Intro

This is the first in a series of small articles about what is new in Silverlight 4 and Expression Blend 4. The series is build around a open source demo application SilverAmp which is available on http://SilverAmp.CodePlex.com.

 

MVVM Project and Item Templates

Expression Blend has got a new project template to get started with a Model-View-ViewModel project  easily. The template provides you with a View and a ViewModel bound together. It also adds the ViewModel to the SampleData of your project. It is available for both Silverlight and Wpf.

clip_image002To get going, start a new project in Expression Blend and select Silverlight DataBound Application from the Silverlight project type. In this case I named the project DemoTest1.

clip_image004

The solution now contains several folders:

  • SampleData; which contains a data to show in Blend
  • ViewModels; starts with one file, MainViewModel.cs
  • Views; containing MainView.xaml with codebehind used for binding with the MainViewModel class.
  • and your regular App.xaml and MainPage.xaml

The MainViewModel class contains a sample property and a sample method. Both the property and the method are used in the MainView control. The MainView control is a regular UserControl and is placed in the MainPage.

You can continue on building your applicaition by adding your own properties and methods to the ViewModel and adding controls to the View.

Adding Views with ViewModels is very easy too. The guys at Microsoft where nice enough to add a new Item template too: a UserControl with ViewModel. If you add this new item to the root of your solution it will add the .xaml file to the views folder and a .cs file to the ViewModels folder.

image

Conclusion

The databound Application project type is a great to get your MVVM based project started. It also functions a great source of information about how to connect it all together.

 

Expression Studio 4 Community Launch Event

Event

On June 7th Expression Studio 4 will be launched at the Internet Week in New York. One day later, on June 8th, the Dutch Silverlight and Expression User Group SIXIN organizes the Dutch Community Launch in collaboration with Microsoft and Centric at Centric’s office in IJsselstein. To celebrate the 4 Expression release we have two interesting speakers. In addition, we give three packages Expression Studio and more great gifts away.

 

Program

The preliminary program for the evening is as follows:

  • 5:45 p.m. – Food, drinks and networking
  • 6:45 p.m. – Reception and Introduction by Koen Zwikstra, co-founder of SIXIN and Silverlight MVP
  • 7:00 p.m. – Building Silverlight applications using the new features of Expression Blend by Loek van den Ouweland, founder and web designer for Toverstudio
  • 8:00 p.m. – Break
  • 8:30 p.m. – Tour Encoder and Expression Web by Antoni Dol, senior designer at Macaw
  • 9:30 p.m. – Networking while enjoying a drink

 

 

Ask your question to one of the speakers

 

If you have a question to one of the speakers, then you can by email (info@sixin.nl) or thru Twitter. Send an email with subject # expression4 or send a tweet @ sixinUG and use it to hashtag # expression4.

 

Register

To register for this event or to get more information you can go to the SIXIN meetings page here.

SixinLogo

 

Special thanks to our sponsors:

 

 

 

Share

Building a “real” extension for Expression Blend

Last time I showed you how to get started building extensions for Expression Blend. Lets build a useful extension this time and go a bit deeper into Blend.

  • Source of project  => here
  • Compiled dll => here (extract into /extensions folder of Expression Blend)

 

The Extension

When working on large Xaml files in Blend it’s often hard to find a specific control in the "Objects and Timeline Pane”. An extension that searches the active document and presents all elements that satisfy the query would be helpful. When the user starts typing a search query a search will be performed and the results are shown in the list. After the user selects an item in the results list, the control in the "Objects and Timeline Pane” will be selected. Below is a sketch of what it is going to look like.

image

 

The Solution

Create a new WPF User Control project as shown in the earlier tutorial in the Configuring the extension project section, but name it AdvancedSearch this time. Delete the default UserControl1.Xaml to clear the solution (a new user control will be added later thought, but adding a user control is easier then renaming one).

Create the main entry point of the addin by adding a new class to the solution and naming this  AdvancedSearchPackage. Add a reference to Microsoft.Expression.Extensibility and to System.ComponentModel.Composition . Implement the IPackage interface and add the Export attribute from the MEF to the definition. While you’re at it. Add references to Microsoft.Expression.DesignSurface, Microsoft.Expression.FrameWork and Microsoft.Expression.Markup. These will be used later.

The Load method from the IPackage interface is going to create a ViewModel to bind to from the UI. Add another class to the solution and name this AdvancedSearchViewModel. This class needs to implement the INotifyPropertyChanged interface to enable notifications to the view.  Add a constructor to the class that takes an IServices interface as a parameter.

Create a new instance of the AdvancedSearchViewModel in the load method in the AdvanceSearchPackage class. The AdvancedSearchPackage class should looks like this now:

 

using System.ComponentModel.Composition;
using Microsoft.Expression.Extensibility;
 
namespace AdvancedSearch
{
    [Export(typeof(IPackage))]
    public class AdvancedSearchPackage:IPackage
    {
 
        public void Load(IServices services)
        {
            new AdvancedSearchViewModel(services);            
        }
 
        public void Unload()
        {
            
        }
    }
}

 

Add a new UserControl to the project and name this AdvancedSearchView. The View will be created by the ViewModel, which will pass itself to the constructor of the view. Change the constructor of the View to take a AdvancedSearchViewModel object as a parameter. Add a private field to store the ViewModel and set this field in the constructor. Point the DataContext of the view to the ViewModel. The View will look something like this now:

 

namespace AdvancedSearch
{    
    public partial class AdvancedSearchView:UserControl
    {
        private readonly AdvancedSearchViewModel _advancedSearchViewModel;
 
        public AdvancedSearchView(AdvancedSearchViewModel advancedSearchViewModel)
        {
            _advancedSearchViewModel = advancedSearchViewModel;
            InitializeComponent();
            this.DataContext = _advancedSearchViewModel;
        }
    }
}

 

The View is going to be created in the constructor of the ViewModel and stored in a read only property.

 

        public FrameworkElement View
        {
            get; private set;
        }
 
        public AdvancedSearchViewModel(IServices services)
        {
            _services = services;
            View = new AdvancedSearchView(this);
        }

The last thing the solution needs before we’ll wire things up is a new class, PossibleNode. This class will be used later to store the search results. The solution should look like this now:

 

image

Adding UI to the UI

The extension should build and run now, although nothing is showing up in Blend yet. To enable the user to perform a search query add a TextBox and a ListBox to the AdvancedSearchView.xaml file. I’ve set the rows of the grid too to make them look a little better. Add the TextChanged event to the TextBox and the SelectionChanged event to the ListBox, we’ll need those later on.

  <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="32" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox TextChanged="SearchQueryTextChanged" 
                 HorizontalAlignment="Stretch" 
                 Margin="4" 
                 Name="SearchQuery" 
                 VerticalAlignment="Stretch" />
        <ListBox SelectionChanged="SearchResultSelectionChanged"
                 HorizontalAlignment="Stretch"
                 Margin="4"
                 Name="SearchResult"
                 VerticalAlignment="Stretch" 
                 Grid.Row="1" />
    </Grid>

 

This will create a user interface like:

image

To make the View show up in Blend it has to be registered with the WindowService. The GetService<T> method is used to get services from Blend, which are your entry points into Blend.When writing extensions you will encounter this method very often. In this case we’re asking for an IWindowService interface. The IWindowService interface serves events for changing windows and themes, is used for adding or removing resources and is used for registering and unregistering Palettes. All panes in Blend are palettes and are registered thru the RegisterPalette method.

The first parameter passed to this method is a string containing a unique ID for the palette. This ID can be used to get access to the palette later.

The second parameter is the View.

The third parameter is a title for the pane. This title is shown when the pane is visible. It is also shown in the window menu of Blend.

The last parameter is a KeyBinding. I have chosen Ctrl+Shift+F to call the Advanced Search pane. This value is also shown in the window menu of Blend.

 

services.GetService<IWindowService>().RegisterPalette(
    "AdvancedSearch",
    viewModel.View,
    "Advanced Search",
    new KeyBinding
    {
        Key = Key.F,
        Modifiers = ModifierKeys.Control | ModifierKeys.Shift
    }
);
 

You can compiler and run now. After Blend starts you can hit Ctrl+Shift+F or go the windows menu to call the advanced search extension.

Searching for controls

The search has to be cleared on every change of the active document. The DocumentServices fires an event every time a new document is opened, a document is closed or another document view is selected. Add the following line to the constructor of the ViewModel to handle the ActiveDocumentChanged event:

 

_services.GetService<IDocumentService>().ActiveDocumentChanged += ActiveDocumentChanged;

 

And implement the ActiveDocumentChanged method:

 

private void ActiveDocumentChanged(object sender, DocumentChangedEventArgs e)
{
}

 

 

To get to the contents of the document we first need to get access to the “Objects and Timeline” pane. This pane is registered in the PaletteRegistry in the same way as this extension has registered itself. The palettes are accessible thru an associative array. All you need to provide is the Identifier of the palette you want. The Id of the “Objects and Timeline” pane is “Designer_TimelinePane”. I’ve included a list of the other default panes at the bottom of this article. Each palette has a Content property which can be cast to the type of the pane.

 

var timelinePane = (TimelinePane)_services.GetService<IWindowService>()
                        .PaletteRegistry["Designer_TimelinePane"]
                        .Content;

 

Add a private field to the top of the AdvancedSearchViewModel class to store the active SceneViewModel. The SceneViewModel is needed to set the current selection and to get the little icons for the type of control.

 

private SceneViewModel _activeSceneViewModel;

 

When the active SceneViewModel changes, the ActiveSceneViewModel is stored in this field. The list of possible nodes is cleared and an PropertyChanged event is fired for this list to notify the UI to clear the list. This will make the eventhandler look like this:

private void ActiveDocumentChanged(object sender, DocumentChangedEventArgs e)
{
    var timelinePane = (TimelinePane)_services.GetService<IWindowService>()
                                       .PaletteRegistry["Designer_TimelinePane"].Content;
 
    _activeSceneViewModel = timelinePane.ActiveSceneViewModel;
    PossibleNodes = new List<PossibleNode>();
    InvokePropertyChanged("PossibleNodes");    
}

The PossibleNode class used to store information about the controls found by the search. It’s a dumb data class with only 3 properties, the name of the control, the SceneNode and a brush used for the little icon. The SceneNode is the base class for every possible object you can create in Blend, like Brushes, Controls, Annotations, ResourceDictionaries and VisualStates. The entire PossibleNode class looks like this:

 

using System.Windows.Media;
using Microsoft.Expression.DesignSurface.ViewModel;
 
namespace AdvancedSearch
{
    public class PossibleNode
    {        
        public string Name { get; set; }        
        public SceneNode SceneNode { get; set; }
        public DrawingBrush IconBrush { get; set; }
    }
}

 

Add these two methods to the AdvancedSearchViewModel class:

 

public void Search(string searchText) { }
public void SelectElement(PossibleNode node){ }

 

Both these methods are going to be called from the view. The Search method performs the search and updates the PossibleNodes list.  The controls in the active document can be accessed thru TimeLineItemsManager class. This class contains a read only collection of TimeLineItems. By using a Linq query the possible nodes are selected and placed in the PossibleNodes list.

 

var timelineItemManager  = new TimelineItemManager(_activeSceneViewModel);
PossibleNodes =
    new List<PossibleNode>(
        (from d in timelineItemManager.ItemList
         where d.DisplayName.ToLowerInvariant().StartsWith( searchText.ToLowerInvariant())
         select new PossibleNode()
         {
             IconBrush = d.IconBrush,
             SceneNode = d.SceneNode,
             Name = d.DisplayName
         }).ToList()
    );
InvokePropertyChanged(InternalConst.PossibleNodes);

 

The Select method is pretty straight forward. It contains two lines.The first to clear the selection. Otherwise the selected element would be added to the current selection. The second line selects the nodes. It is given a new array with the node to be selected.

 

_activeSceneViewModel.ClearSelections();
_activeSceneViewModel.SelectNodes(new[] { node.SceneNode });

 

The last thing that needs to be done is to wire the whole thing to the View. The two event handlers just call the Search and SelectElement methods on the ViewModel.

 

private void SearchQueryTextChanged(object sender, TextChangedEventArgs e)
{
    _advancedSearchViewModel.Search(SearchQuery.Text);
}
 
private void SearchResultSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(e.AddedItems.Count>0)
    {
        _advancedSearchViewModel.SelectElement(e.AddedItems[0] as PossibleNode);
    }
}

 

The Listbox has to be bound to the PossibleNodes list and a simple DataTemplate is added to show the selection. The IconWithOverlay control can be found in the Microsoft.Expression.DesignSurface.UserInterface.Timeline.UI namespace in the Microsoft.Expression.DesignSurface assembly. The ListBox should look something like:

 

<ListBox SelectionChanged="SearchResultSelectionChanged"
         HorizontalAlignment="Stretch" Margin="4"
         Name="SearchResult" VerticalAlignment="Stretch" Grid.Row="1" 
         ItemsSource="{Binding PossibleNodes}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">             
                <tlui:IconWithOverlay Margin="2,0,10,0"
                                      Width="12" Height="12" 
                                      SourceBrush="{Binding Path=IconBrush, Mode=OneWay}" 
                                   />
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
            
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

 

Compile and run. Inside Blend the extension could look something like below.

image

What’s Next

When you’ve got the extension running. Try placing breakpoints in the code and see what else is in there. There’s a lot to explore and build extension on. I personally would love an extension to search for resources.

Last but not least, you can download the source of project here.  If you have any questions let me know.

If you just want to use this extension, you can download the compiled dll here. Just extract the . zip into the /extensions folder of Expression Blend.

Notes

Target framework

I ran into some issues when using the .NET Framework 4 Client Profile as a target framework. I got some strange error saying certain obvious namespaces could not be found, Microsoft.Expression in my case. If you run into something like this, try setting the target framework to .NET Framework 4 instead of the client version.

 

Identifiers of default panes

 

 

 

Identifier Type Title
Designer_TimelinePane TimelinePane Objects and Timeline
Designer_ToolPane ToolPane Tools
Designer_ProjectPane ProjectPane Projects
Designer_DataPane DataPane Data
Designer_ResourcePane ResourcePane Resources
Designer_PropertyInspector PropertyInspector Properties
Designer_TriggersPane TriggersPane Triggers
Interaction_Skin SkinView States
Designer_AssetPane AssetPane Assets
Interaction_Parts PartsPane Parts
Designer_ResultsPane ResultsPane Results

Building extensions for Expression Blend 4 using MEF

Introduction

Although it was possible to write extensions for Expression Blend and Expression Design, it wasn’t very easy and out of the box only one addin could be used. With Expression Blend 4 it is possible to write extensions using MEF, the Managed Extensibility Framework.

Until today there’s no documentation on how to build these extensions, so look thru the code with Reflector is something you’ll have to do very often. Because Blend and Design are build using WPF searching the visual tree with Snoop and Mole belong to the tools you’ll be using a lot exploring the possibilities.

Scott Barnes has written an article on his blog about How to hack Expression Blend. It provides some information on how to get to know more about the inside of Blend.

Configuring the extension project

Extensions are regular .NET class libraries. To create one, load up Visual Studio 2010 and start a new project. Because Blend is build using WPF, choose a WPF User Control Library from the Windows section and give it a name and location. I named mine DemoExtension1.

image

Because Blend looks for addins named *.extension.dll  you’ll have to tell Visual Studio to use that in the Assembly Name. To change the Assembly Name right click your project and go to Properties. On the Application tab, add .Extension to name already in the Assembly name text field.image

To be able to debug this extension, I prefer to set the output path on the Build tab to the extensions folder of Expression Blend. This means that everything that used to go into the Debug folder is placed in the extensions folder. Including all referenced assemblies that have the copy local property set to false.

image One last setting. To be able to debug your extension you could start Blend and attach the debugger by hand. I like it to be able to just hit F5. Go to the Debug tab and add the the full path to Blend.exe in the Start external program text field.image

Extension Class

Add a new class to the project.  This class needs to be inherited from the IPackage interface. The IPackage interface can be found in the Microsoft.Expression.Extensibility namespace. To get access to this namespace add Microsoft.Expression.Extensibility.dll to your references. This file can be found in the same folder as the (Expression Blend 4 Beta) Blend.exe file. Make sure the Copy Local property is set to false in this reference. After implementing the interface the class would look something like:

using Microsoft.Expression.Extensibility;
namespace DemoExtension1
{
    public class DemoExtension1:IPackage
    {
        public void Load(IServices services)
        {            
        }
        public void Unload()
        {         
        }
    }
}

 

 

 

These two methods are called when your addin is loaded and unloaded. The parameter passed to the Load method, IServices services, is your main entry point into Blend. The IServices interface exposes the GetService<T> method. You will be using this method a lot. Almost every part of Blend can be accessed thru a service. For example, you can use to get to the commanding services of Blend by calling GetService<ICommandService>() or to get to the Windowing services by calling GetService<IWindowService>().

To get Blend to load the extension we have to implement MEF. (You can get up to speed on MEF on the community site or read the blog of Mr. MEF, Glenn Block.)  In the case of Blend extensions, all that needs to be done is mark the class with an Export attribute and pass it the type of IPackage. The Export attribute can be found in the System.ComponentModel.Composition namespace which is part of the .NET 4 framework. You need to add this to your references.

using System.ComponentModel.Composition;
using Microsoft.Expression.Extensibility;
 
namespace DemoExtension1
{
    [Export(typeof(IPackage))]
    public class DemoExtension1:IPackage
    {

 

 

 

Blend is able to find your addin now.

Adding UI

The addin doesn’t do very much at this point. The WPF User Control Library came with a UserControl so lets use that in this example. I just drop a Button and a TextBlock onto the surface of the control to have something to show in the demo.image

To get the UserControl to work in Blend it has to be registered with the WindowService.  Call GetService<IWindowService>() on the IServices interface to get access to the windowing services. To get access to the IWindowService interface, add a reference to Microsoft.Expression.Framework to the project. The UserControl will be used in Blend on a Palette and has to be registered to enable it. This is done by calling the RegisterPalette on the IWindowService interface and passing it an identifier, an instance of the UserControl and a caption for the palette.

public void Load(IServices services)
{
    IWindowService windowService = services.GetService<IWindowService>();
    UserControl1 uc = new UserControl1();
    windowService.RegisterPalette("DemoExtension", uc, "Demo Extension");
}

 

 

 

After hitting F5 to start debugging Expression Blend will start. You should be able to find the addin in the Window menu now.

imageActivating this window will show the “Demo Extension” palette with the UserControl, style according to the settings of Blend.image

Now what?

Because little is publicly known about how to access different parts of Blend adding breakpoints in Debug mode and browsing thru objects using the Quick Watch feature of Visual Studio is something you have to do very often. This demo extension can be used for that purpose very easily.

Add the click event handler to the button on the UserControl. Change the contructor to take the IServices interface and store this in a field. Set a breakpoint in the Button_Click method.

public partial class UserControl1 : UserControl
{
    private readonly IServices _services;
 
    public UserControl1(IServices services)
    {
        _services = services;
        InitializeComponent();
    }
 
    private void button1_Click(object sender, RoutedEventArgs e)
    {
    }
}

 

 

 

Change the call to the constructor in the load method and pass it the services property.

public void Load(IServices services)
{
    IWindowService service = services.GetService<IWindowService>();
    UserControl1 uc = new UserControl1(services);
    service.RegisterPalette("DemoExtension", uc, "Demo Extension");
}

Hit F5 to compile and start Blend. Got to the window menu and start show the addin. Click on  the button to hit the breakpoint. Now place the carrot text _services text in the code window and hit Shift+F9 to show the Quick Watch window. Now start exploring and discovering where to find everything you need. image

 

More Information

The are no official resources available yet. Microsoft has released one extension for expression Blend that is very useful as a reference, the Microsoft Expression Blend® Add-in Preview for Windows® Phone. This will install a .extension.dll file in the extension folder of Blend. You can load this file with Reflector and have a peek at how Microsoft is building his addins.

Conclusion

I hope this gives you something to get started building extensions for Expression Blend. Until Microsoft releases the final version, which hopefully includes more information about building extensions, we’ll have to work on documenting it in the community.

StarterKits for Silverlight and Expression

StarterKits for Silverlight and the Expression Tools

Lately I’ve seen some tweets passing by with links to various StarterKits. I’ve decided to "Bing” around a little and find out what these people were talking about. There are quite a few StarterKits available on various topics. I’ve listed a few below, old and new ones, that I find relevant to my fields of interest: Silverlight and the Expression Blend, Design and Web.


expression blend 3 icon

Building a Zune Website with Expression Blend 3 StarterKit

In this lab you will learn how to use Expression Blend and Visual Studio to build a Zune mini-website

This hands-on-lab explains how to build a Silverlight application to view a Zune in various colors. The labs shows a couple of Silverlight concepts like data binding, Perspective 3D and Out of Browser. It contains four exercises:

  1. Control styling and templating
  2. Save files to disc
  3. Perspective 3D
  4. Out of browser

> Download StarterKit

Result of Building a Zune Website with Expression Blend 3 StarterKit


expression blend 3 icon

Creating a ColorSwatch With Expression Blend 3 Starter Kit

Learn how to create a fun and colorful color swatch control using Expression Blend 3 custom layout controls. In this Starter Kit you will find assets, labs and a video collection.

This StarterKit explains how to build a Color Swatch control in detail. The kit contains 10 modules each with a Word document walking you through ever step, a video and Visual Studio solution containing the code:

  1. Using Blends Sample Data Feature and Importing XML Data into Expression Blend
  2. Creating the Style for the SwatchListBox
  3. Binding the Values to the XML Data Object
  4. Importing a Custom Panel into the Project and using it for the List Box
  5. Creating the Details Balloon
  6. Binding Data to the Details Balloon
  7. Adding the Details Balloon VisualStateGroup
  8. Adding Events
  9. Adding and Using the ListBoxSentToTop.cs Behavior
  10. Testing and Modifying the Color Swatch Application

> Live Demo

> Download StarterKit

image

 


expression_web_3_icon

Expression Web 3 Super Preview Starter Kit

Use this Expression Web 3 Super Preview Starter Kit to become familiar with Super Preview.

This StarterKit talks you thru a lot of features of Super Preview, which is part of Expression Web 3. The Kit contains four modules, each made out of a video, a Word document and the assets needed. The module’s are titled:

  1. An Introduction to SuperPreview
  2. Defining Baseline Browsers and Comparing Image Mockups
  3. Identifying the Source of Layout Problems
  4. Working with the DOM View

> Download StarterKit

image


expression_web_3_icon

Microsoft® Expression® Design Portfolio Starter Kit

Get hands-on support in standards-compliant Web design.

This StarterKit contains the code for an Asp.net site for a design portfolio and a document on how to customize it.

This StarterKit is an older one, but still useful. It’s not as comprehensive as the newer ones. I think it’s a nice foundation to build a new site on.

> Download StarterKit   clip_image002


expression_web_3_icon

Silverlight Support Web 3 StarterKit

 

The download site for this StarterKit contains little information about the Kit. The contents however is surprisingly extensive. It explains stuff about Silverlight, Expression Web and SuperPreview, among other things. The Kit contains six modules each with a video, a Word document and example code.

  1. Introduction to Inserting Silverlight Content with Expression Web 3
  2. Inserting Silverlight Content into a Web Page Using Expression Web 3
  3. Using Dynamic Web Templates in Expression Web 3
  4. Inserting Silverlight Video into a Web Page Using Expression Web 3
  5. Adding Deep Zoom Content to a Web Page Using Expression Web 3
  6. Using Expression Web’s Publishing Feature to Deploy Your Web Site

> Download StarterKit

image


expression blend 3 icon

Prototyping with Sketchflow in Expression Blend 3 Starter Kit

 

New in expression Blend 3 is SketchFlow. This extensive StarterKit explains a how to build a prototype of a Snowboard shop in Silverlight. The Kit contains all videos, guides and example code you need. The Kit is divided into 12 modules:

  1. Introducing SketchFlow
  2. Adding Navigation Screens in SketchFlow
  3. Building a Basic Layout in SketchFlow
  4. Adding SketchStyle Controls to Enhance a SketchFlow Layout
  5. Working with Components
  6. Adding Navigation to Buttons in SketchFlow
  7. Working with States in SketchFlow
  8. Working with SketchFlow Animation
  9. Working with Behaviors
  10. Using Sample Data in SketchFlow
  11. Using SketchFlow and SketchFlow Player to Track Feedback
  12. Exporting Your SketchFlow Project

> Download StarterKit

 

image


expression_web_3_icon

Standards Based Websites with Expression Web 3 Starter Kit

Learn how to create standards based websites with Expression Web 3 using this Starter Kit that includes assets, labs and videos.

This StarterKit explains what standards can be used in Expression Web 3 and why you can benefit from them. The guide explains uses of css and html best practices. Again, the Kit contains code, videos and Word documents spread over 10 modules:

  1. Understanding the Benefits of Standards-Based Design with Expression Web
  2. Best Practices for Markup and Using Multiple Style Sheets
  3. Using CSS Properties to Create a Unique Heading in Expression Web
  4. Creating a Site Navigation Bar in CSS Using Expression Web
  5. Creating a Site Navigation Bar in CSS Using Expression Web (Part 2)
  6. Working with Images Using CSS
  7. Create a Two Column Layout with Expression Web (Part 1: CSS Floats)
  8. Create a Two Column Layout with Expression Web (Part 2: CSS Floats)
  9. Modifying CSS Layouts with Margins and Padding
  10. Testing Your Site with Snapshot and SuperPreview

>Download StarterKit

image


 

expression blend 3 icon

Venture Into Gaming Expression Blend 3 Starter Kit

Explore gaming using Microsoft Expression Blend 3 Starter Kit

This last StarterKit is my personal favorite. What’s more fun than building a real game? This one explains everything. From importing assets in Expression Blend to Testing it in SuperPreview. All using Silverlight. This StarterKit is a great place to start if you’re new to Silverlight and the Expression toolset. But even if you’re a more experienced Silverlight developer I recommend reading thru this one. As a lot of other StarterKits, this one contains videos, guides and videos in 10 parts:

  1. Organizing and Importing Assets into Expression Blend
  2. Creating the Game Interface Using Expression Blend 3
  3. Understanding Layout Containers
  4. Creating a UserControl
  5. Adding and Applying Behaviors
  6. Adding Walls and Creating Animations
  7. Animating Controls with the Visual State Manager
  8. Working with Text and Embedding Fonts in Expression Blend
  9. Adding Audio Resources to a Silverlight Game
  10. Publishing and Testing your Silverlight Game

>Download StarterKit

image

 


 

Shout it
Tags van Technorati:
Sixinblogger
Silverlight and Expression Insiders Usergroup
kick it on DotNetKicks.com

9 little new things in Expression Blend 3

When working on some projects and articles in Expression Blend 3 I noticed a few differences with Blend 2 right away. Here are 9 improvements and new features I really like or enjoy having now.

1. Expression Blend now shows the size of your controls even when the width and height are set to Auto:

LittleThing01

2. The assets are placed in a panel now. Although the “old” way of working with asses is still available, this new panel can be left open. Beside that, the assets are grouped in different ways in a tree, which makes them very easy to find.

LittleThing02

3. The is support for Team Foundation Server now. At this point you need to install a hotfix from the knowledge base, but I found this feature very useful. It’s not a little thing, but I ran into this limitation in expression Blend 2 almost daily and I am so glad checking in and out files is possible now.

LittleThing03

 

4. You don’t have to edit .XML files to get your application to run Out-Of-Browser anymore. Just set it thru the Project menu:

LittleThing04

 

5. The recording state is on, when editing visual states for example, is much better to read. In stead of showing the whole line in red, only the border and the center of a little light is red now. A small thing, but nice.

LittleThing05

 

6. The gradient settings can be edited now from the properties panel. Just expand the group to view the advanced properties when editing a gradient. Editing the StartPoint, EndPoint and Transformations has become really easy now.

LittleThing06

7. When writing the article about styling a TreeView I ran into a few bugs in the Hierarchical Data Templates. These are fixed now. Better even, with just one click you can convert your Sample Data into a Hierarchical Collection:

LittleThing07

8. With Silverlight 3 came Behaviors. These, among other items, can be added now from the New Items dialog right inside Blend. Code templates are used so you don’t have to set the whole thing up yourself. Just go to File->New Item…

LittleThing08

9. One last feature I would like to mention is intellisense. When working on smaller projects, you do not have to leave Blend to edit some code. It can be done right in Blend now, which becomes very handy when dealing with events for example. Intellisense even works when editing Xaml files.

LittleThing09

 

There are of course many more new features in Expression Blend 3. Even Very big ones, like SketchFlow. In future tutorials many of these will be explained.

If you haven’t already, go and download the 60 day trail version of Microsoft Expression Blend 3 + SketchFlow RC now and play with it. It’s fun!

Shout it
Tags van Technorati:
dotNed blogger
kick it on DotNetKicks.com

Styling a TreeView in Silverlight 3 and Blend 3

Introduction

Today I would like to show you how to style a TreeView control in Silverlight 3 using Expression Blend 3. The TreeView is a control to visualize hierarchical data structures. If you haven’t got Silverlight 3 and Blend 3, you can find all downloads for Silverlight 3 and Blend 3 here. The TreeView control is available in WPF natively and styling is only a small bit different than in Silverlight. I try to explain one way of doing this and there are others. If you have any questions what so ever or suggestions for other tutorials, please let me know.

Result

Initial Startup

We’ll start by creating a new Silverlight 3 Application project.

NewProject 

Go to the new Assets panel and find select the TreeView control from the controls section.

NewAssetPanel

Add the TreeView to the RootLayout Grid by dragging it from the Asset panel to the edit area. Make it span the entire area by setting the margins to 0, the horizontal and vertical alignment to stretch and the width and height to Auto. At this point nothing is visible, because there’s no data yet.

Sample Data

One of the features I really like in Expression Blend 3 is the generation of sample data. By using sample data you don’t have to wire your application up to a real data source and making it available when designing an application. Often I create sample data in Blend 3 to add it to parts of my production work in Blend 2.

A TreeView uses hierarchical data, which often are collections in collections in collections etc. I would like to have three different types of data all in collections. Create the first collection of data by going to the Data panel, click the Add sample data source icon and select Define New Sample Data…

AddSampleData

Make sure the Enabled sample data when application is running checkbox is checked, so that you can see the result of the styled checkbox when running the application. Accept all other settings and hit the Ok button.

newSampleData

Rename the default collection to RootLevelCollection.

RenameRootCollection

To quickly test you TreeView you can convert the RootLevelCollection to a Hierarchical Collection, which basically means that the collection is referencing itself. To do this, click on the little dropdown list at the end of the RootLevelCollection line and click Convert To Hierarchical Collection.

ConvertToHierarchicalCollection

Immediately a collection is added to the RootLevelCollection. If you open this, you’ll find the same properties as the first level, including the collections. You can open these collections as long as you want.

In this tutorial I would like to show you how to use different templates on different types of levels in you collection. The recursive collection can be removed again by right clicking on the “child” RootLevelCollection and hit Remove.

RemoveRecursiveCollection

Change the type of Property1 to number by clicking on the little abc icon at the end of the line and select number from the dropdown list. Rename the property to NumberProperty.

ChangePropertyToNumber

Add a simple property and by clicking on the plus icon and rename it to NameProperty.

AddSampleSimpleProperty

Change the string format by clicking on the abc icon and select Name from the Format dropdown list.

ChangeStringProperty

Add a new collection to the RootLevelCollection by clicking on the little down arrow on the same line and select Add Collection Property. Rename this to FirstLevelCollection.AddSampleCollection

Repeat the steps above to end up with the following properties:

 

RootLevelCollection

  • NameProperty – Simple Property of String (Format: Name)
  • NumberProperty – Simple Property of Number
  • FirstLevelCollection – Collection Property

FirstLevelCollection

  • CompanyProperty – Simple Property of String(Format: Company Name)
  • NumberProperty – Simple Property of Number
  • UrlProperty – Simple Property of String(Format: Website Url)
  • SecondLevelCollection – Collection Property

SecondLevelCollection

  • ImageProperty – Simple Property of Image
  • NameProperty – Simple Property of String(Format: Name)
  • PhoneProperty –Simple Property of String(Format: Phone number)

The sample data tree should look something like this. I added a few red lines to make the structure of the tree a bit  more clear.

SampleDataTree

To bind the sample data to the TreeView, drag the RootLevelCollection to the TreeView element in the Objects and Timeline Panel. You should see some of the data appear in the tree immediately. although it doesn’t look very much like a tree yet.

Creating Hierarchical Data Templates

To show the data in the best way possible, every type of data needs it’s own Data Template. The HierarchicalDataTemplate, that you might know from WPF. The Silverlight version doesn’t include all methods and properties the WPF version does, but provides an easy way to style hierarchical data.

Due to a bug in Silverlight, Expression Blend will show an error when using nested Hierarchical Data Templates. There seems to be a problem in the xaml parser, which says the xaml is invalid. But it isn’t and the application will run anyway. I’ll show you how to work around this error. Let’s hope this gets fixed in the final release.

This annoying bug has been fixed in the release version! The templates work like they should now. Microsoft has made some big improvements in this area. Everything can be done in Expression Blend 3 now and it can be done without having to write anything in xaml. But, I think I might be useful to learn how the Data Templates are build in xaml and because this was the way it was written in the betas, I’ll stick with that. More tutorials will follow and the creation of templates by right clicking your mouse will be covered without a doubt.

Because the sample data created earlier contains three levels, three collections of a different class, three different data templates are needed to show the data properly. To keep these templates separated and enable the possibility to share the templates between different pages and UserControls very easy, I prefer to put data templates in there own Resource Dictionary. A resource dictionary is a xaml file that contains only resources. To add a new dictionary to your project click File –> New Item… and select Resource Dictionary from the list. If you want you can give it a useful name, for now, just accept the default by clicking Ok.

 NewItem

Now you need to link the new resource dictionary to the TreeView so it can access the templates. Go to the Resource panel and right-click [TreeView]  control, select Link to Resource Dictionary and click ResourceDictionary1.xaml.

LinkToResourceDictionary Right-click ResourceDictionary1.xaml in the resource panel and hit View XAML to open the resource dictionary.

ViewXaml To make use of a HierarchicalDataTemplate xaml, you first need to reference it’s namespace. Do this by adding the following line to the opening ResourceDictionary tag at the beginning of the file:

xmlns:common="clr-namespace:System.Windows;assembly=System.Windows.Controls"

The hierarchical data template has three dependency properties. For now, use only the ItemSource property. The ItemSource property can be bound to the collection used for the next level in the hierarchical tree. In this example this would be the FirstLevelCollection. The contents of the data template are not very special. Just an horizontal oriented StackPanel with two TextBlocks. The first one is bound to the NumberProperty and is slightly bigger than the other. That one is bound to the NameProperty of the root sample data class. Add a small margin to give the TextBlocks a little more space.

<common:HierarchicalDataTemplate x:Key="RootLevel"
         ItemsSource="{Binding Path=FirstLevelCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0"
                   Text="{Binding Path=NumberProperty}" 
                   FontWeight="Bold" FontSize="12" />
        <TextBlock Margin="3,0,5,0"
                   Text="{Binding Path=NameProperty}" />
    </StackPanel>
</common:HierarchicalDataTemplate>

This data template needs to be known by the TreeView. Right-click on the TreeView control in the Objects and Timeline Panel and go to Edit Other Templates –> Edit Generated Items(ItemTemplate) –> Apply Resource and select RootLevel from the list.

SetItemTemplate You should see some changes to the tree now. It doesn’t look a lot like a tree yet. To style the second level of the tree, add another HierarchicalDataTemplate to the ResourceDictionary. This template has to be defined before it’s used, which will be by the root template. It looks similar to the template above, only the key and the bindings are different. This template has it’s ItemSource bound to the collection for the second level, SecondLevelCollection.

<common:HierarchicalDataTemplate x:Key="Level1"
        ItemsSource="{Binding Path=SecondLevelCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0"
                   Text="{Binding Path=NumberProperty}" />
        <TextBlock Margin="3,0,3,0"
                   Text="{Binding Path=CompanyProperty}" />
        <TextBlock Margin="3,0,5,0"
                   Text="{Binding Path=UrlProperty}" />
    </StackPanel>
</common:HierarchicalDataTemplate> 

At this point nothing will happen, because the two templates need to be connected. The HierarchicalDataTemplate uses a dependency property, similar to the one on the TreeView, to do this: ItemTemplate. To use the Level1 data template as an item template add the following line to the start tag of the RootLevel template:

<common:HierarchicalDataTemplate
            x:Key="RootLevel"
            ItemsSource ="{Binding Path=FirstLevelCollection}"
            ItemTemplate="{StaticResource Level1}">
...

There’s only the second level of the template left to style. It’s similar to the other two. Bind the source of the image to the ImageProperty and set it’s width and height to 25.

<common:HierarchicalDataTemplate x:Key="Level2">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,0,3,0"
                   FontStyle="Italic"
                   Text="{Binding Path=NameProperty}" />
        <TextBlock Margin="3,0,3,0"
                   Text="{Binding Path=PhoneProperty}" />
        <Image Margin="3,0,5,0"
               Height="25" Width="25"
               Source="{Binding Path=ImageProperty}"/>
    </StackPanel>
</common:HierarchicalDataTemplate>

Don’t forget to set the ItemSource property on the Level1 template to Level2 when running the application.

To quickly access the templates for editing. Select the MainControl.Xaml file for editing and go to the Resource panel. When you expand the ResourceDictionary1.xaml dictionary file, you can open the templates for editing by clicking on the button next to the template names:

QuickEditTemplate

When running the application should look something like:

RunningApp1 It looks like a tree now, but not a very awesome one. Let’s style it a little further.

Creating Control Templates

To make the tree look a little better, you need to change its ItemContainerStyle.

EditItemContainerStyle

Give it a fancy name. To add it to the ResourceDictionary select the Resource dictionary radio button in the define in section. Hit OK to confirm and close the window.

newContainerStyle

To get to the template, right-click the Style element and select Edit Control Parts –> Edit Template.EditContainerStyleTemplateThe TreeViewItemTemplate consists of 3 important parts: the Header, which represents one item; ItemsHost, which represents the child items of the header (these items can be headers with children too); and the ExpanderButton, which is the indicator if a header is expander or not. First, lets change the look and feel of the ExpanderButton.

Right-Click the ExpanderButton element and select Edit Control Parts(Template) –> Edit Template.

editExpanderButtonTemplate The default template contains a couple of grids and two paths. These are unnecessary, so delete the [Grid] element including the two paths. The paths were animated, so ignore the message about this.

Add a Border to the Root grid element. Start by giving it a fixed width and height of 24. Change its Corner Radii to 8,3,3,8 and its Border Thickness to 1,2,1,1 to give it a little flow to the right. Change the Border Color to a gradient, starting and ending on a darkish blue color like #FF0D0A45. Add a Gradient Stop at about 20% and make this a little whiter than the start and end. Set the Background Color to a SolidBrush and change its color to a lighter version of the gradient, like #FF5C5A88.

Next, add a Grid to the border and make sure all properties are set to their defaults. Add two TextBlocks to he grid and name them PlusSign and MinusSign. Type in the PlusSign textblock a “ + “ and in the MinusSign textblock a “ – “. Set the Horizontal- and the Vertical Alignment on both textblocks to Center. Change their fonts to Verdana, make them Bold and increase their sizes to 18. Set the Foreground Color to full white on both. Hide the MinusSign by default by setting its opacity to 0. This only has to become visible when the tree is expanded.

PlusSign

The Xaml should look something like:

<Border x:Name="border"
        BorderThickness="1,1,2,1"
        Width="24" Height="24"
        CornerRadius="8,3,3,8"
        Background="#FF5C5A88">
     <Border.BorderBrush>
        <LinearGradientBrush EndPoint="0.5,1"
                             StartPoint="0.5,0">
            <GradientStop Color="#FF0D0A45" Offset="0"/>
            <GradientStop Color="#FF0D0A45" Offset="1"/>
            <GradientStop Color="#FF3A385B" Offset="0.2"/>
        </LinearGradientBrush>
    </Border.BorderBrush>
    <Grid>
        <TextBlock x:Name="PlusSign"
                   Text="+" TextWrapping="Wrap"
                   FontFamily="Verdana" FontWeight="Bold"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Foreground="#FFFFFFFF" FontSize="18"/>
        <TextBlock x:Name="MinusSign"
                   Text="-" TextWrapping="Wrap"
                   FontFamily="Verdana" FontWeight="Bold"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="18" Opacity="0"
                   Foreground="#FFFFFFFF"/>
    </Grid>
</Border>

The change to looks of ExpanderButton when it is checked, you can use the Visual State Manager. Go to the States panel and select Checked under the CheckStates Visual State Group. Notice the red border around the drawing area, this indicates that every change you make is recorded and stored in this particular Visual State.

 CheckedState

 

With the Checked State selected, change the Opacity of the MinusSign element to 100 and of the PlusSign to 0. At this point the MinusSign is visible when the TreeView is expanded.  Change the Corner Radii of the Border to 8,8,3,3 and the Thickness to 1,1,1,2. minusSign

The Xaml for the Checked State is placed inside the code for the Visual State Manager. It should look something like:

<vsm:VisualState x:Name="Checked">
    <Storyboard>
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                       Duration="00:00:00.0010000"
                                       Storyboard.TargetName="MinusSign"
                                       Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                       Duration="00:00:00.0010000"
                                       Storyboard.TargetName="PlusSign"
                                       Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
                                       Duration="00:00:00.0010000"
                                       Storyboard.TargetName="border"
                                       Storyboard.TargetProperty="(Border.CornerRadius)">
            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                <DiscreteObjectKeyFrame.Value>
                    <CornerRadius>8,8,3,3</CornerRadius>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
                                       Duration="00:00:00.0010000"
                                       Storyboard.TargetName="border"
                                       Storyboard.TargetProperty="(Border.BorderThickness)">
            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                <DiscreteObjectKeyFrame.Value>
                    <Thickness>1,1,1,2</Thickness>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
         </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</vsm:VisualState>

To make the tree a bit more user friendly, you want to highlight the ExpanderButton when the mouse cursor is hovering. Got to the States panel and select MouseOver this time. It’s in the  Common States Visual State Group. To keep the same gradient it would be nice if you could only shift the colorization. You can do this by changing the color mode setting. If you look at a color editor, notice that there the R, G and B are underlined. When you click on one a small listbox pops up and you can change the color mode. If you change it to HSL, Hue – Saturation – Lightness, you have the possibility to shift the Hue, which happens to be the colorization.

Rgb2Hsl

Change the Hues for the the Border gradient  and for the Background color to 48.

To position the ToggleButton properly, remove the second column of the root Grid of the template and set the width of the first column to 32 and the with of the now second column to 1 star. The same goes for the two rows, the first to 32 pixels and the second to 1 star. Making this piece of xaml look something like:

<Grid Background="{x:Null}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="32"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="32"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
...

Click the button with the arrow next to ToggelButton Template in the Objects and Timeline panel to leave the template.

ReturnScope

To place the child items in a container, right click the ItemsHost element in the Objects and Timeline panel and select Group into… and select Grid, or press Ctrl+G on the keyboard. Make sure all properties are set to their defaults, the Grid tag in xaml should be empty. Next, right click the Grid you’ve just added and go to Group into… again, but this time select Border. Give this border a gradient for its Background brush and make it go from an almost white purple to just a little darker than that, like from #FFD4D2F9 to #FF908BEE. The BorderBrush for this border will be the same as the border used for the ToggleButton explained earlier. Set the border Thickness to 1 on all four to make the border visible. Change the border’s CornerRadius to 1,4,8,4 to give a modern look.

Change the location of the border to row 1, column 1, rowspan 1 and gridspan 1. To make the border indent less that 32 pixels, but keeping it bound to the second column, change the Left Margin to –27. This will make it look like its indentation is only 5 pixels, but, to keep the TreeView work correctly, resize it only to the second column. Set the Left Padding to 5 to let the contents of the border indent even a little more.

When you run the application at this point, a small line will be shown for every item of the TreeView. This is cause by the Visual State Manager only hiding and showing the ItemsHost at this time. To make the entire border disappear, copy the following two properties from the ItemsHost to the Border in the xaml editor.

Visibility="Collapsed"
x:Name="ItemsHost" 

The border will be named ItemsHost now. And when you run the application, the border should become visible when TreeView Items are expanded. It is possible you’ll see an error when the properties are removed from the ItemsHost. I assume this is cause by the same bug as with the Hierarchical templates. If you want to make the border visible again, move these properties back to the ItemsHost, which is now called ItemsPresenter,  its default name. If you want to see the Border with its contents again, select the Expanded state in the Visual State Manager.

Expanded

I personally like a shiny edge on borders. It’s very easy add that little spark. Start by adding a rectangle to the grid and place this above the ItemsPresenter(this used to be ItemsHost) element in the same grid. Keep the width and height of 100. Set the Fill to No Brush to make its background transparent. The Stroke brush has to be set to a gradient, going from fully transparent white to 50% transparent white. Set its radii to 8 and its StrokeThickness to 1.  Make it Horizontally align to the Right  and the Vertical alignment to the Bottom. Set the right and bottom margins to 3, keeping the left and top margins 0. The last part is best done in xaml and has to do with the start and end positions of the gradient. The gradient needs a StartPoint of 0.7, 0.7 and an EndPoint of 1.0,1.0. The xaml for the rectangle:

<Rectangle Fill="{x:Null}"
           RadiusX="8" RadiusY="8"
           VerticalAlignment="Bottom"
           HorizontalAlignment="Right"
           Width="100" Height="100"
           Margin="0,0,3,3">
    <Rectangle.Stroke>
        <LinearGradientBrush
                    EndPoint="1,1"
                    StartPoint="0.7,0.7">
            <GradientStop Color="#00FFFFFF" Offset="0"/>
            <GradientStop Color="#7FFFFFFF" Offset="1"/>
        </LinearGradientBrush>
    </Rectangle.Stroke>
</Rectangle>

Before running the application, make sure you’ve cut-pasted the ItemTemplates to the right places in the Hierarchical data templates and set the Visibility and Name properties correctly on the Border in the TreeViewContainerStyle. You can just hit F5 in the new release and your application will run line a charm.

Where to go from here

This tutorial only showed what can be done styling the TreeView, which templates are available, and where can they be found. Imagine what you can do with real data, creating a style that looks and feels one with the data. You can even go beyond the basic TreeView and create multiple columns or a Tab-like style.

One place I want to mention is the blog of Bea Stollnitz. On her blog she give a lot of information and explanation about TreeViews and ListViews, for WPF and Silverlight.

The code for the tutorial can be downloaded here.

Shout it dotNed blogger
kick it on DotNetKicks.com

Categories

Twitter