Home Contact

Timmy Kokke

…just sorting my bubbles…

News




Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged

Twitter












Tag Cloud


Archives

Post Categories

Image Galleries

Silverlight

Syndication:

Expression Blend Tips and Tricks at Mix11?

I was a bit surprised when I got an email from the Mix11 team congratulating me on my session proposal making the first cut. So now it’s up to the you to vote on your favorite sessions. After voting for mine, you can vote on 9 other sessions Winking smile. The entire list can be found here. The voting period ends on February 4, 2011.

 

My session will be focused on Expression Blend. I’ll be talking about the Visual State Manager, Sample Data and Behaviors. And I show some helpful features along way.  

 

So go and vote now, and I hope to see you at Mix11!

 

Expression Blend Tips and Tricks

Learn how Expression Blend can help you when building WPF, Silverlight or WP7 applications. Find out how to use behaviors and how to build them. See how sample data can be used and created. And how you can use the visual state manager to set and animate the properties of the controls in your applications.

 

300x250_Mix11_011011_US_b



HTML5 – An Introduction - Code and Slides

Today I gave a talk about HTML5 at the UNIT4 DevDay. Thanks to UNIT4 for giving me this opportunity and thanks to everyone who attended my session!

Although HTML5 far from completed, it is a lot of fun to work with. Not all tags used in HTML5 are supported by the browsers. You can try the demos on different browsers to see if they work.

  • Download the code here.
  • Download the slides here.

For those at UNIT4 who missed this presentation, I will repeat it at UNIT4 Internet Solutions and at UNIT4 Oost Nederland.  So maybe I’ll see you there. The dates this will happen follow as soon as they are known.

If you have any questions, ideas, suggestions or a shout-out, just let me know by writing a comment below this post, sending me an email or contacting my though twitter @Sorstkoot.

Technorati Tags:


NuGet

You are reading an old version of my weblog. Please update your bookmarks to http://www.timmykokke.com

If you often use open source libraries you probably have a large library with various tools, like I do. NuGet is an extension for visual studio that enables you to install, uninstall and upgrade open source packages into your application very easily. Say for example you want to use MvvmLight or Ninject in your project, with NuGet it’s nothing more that tell it to add the package to your project.

NuGet

NuGet (formerly known as NuPack) is a free, open source developer focused package management system for the .NET platform.

You can download the .vsix extension at http://nuget.codeplex.com.

image

After installing it you can start adding packages to your project in two ways. The first is by right clicking in the Solution Explorer and selecting the Add Library Package Reference… option.

image

This will present you with a dialog where you can find and install a package. To see the package available, select the Online option from the list on the left. You can use the text box on the top right to filter the list to get to the package you want to use. Hit the install button to add the package to your project.

image

To remove a package, go to the same window. The installed packages are shown on the first page. Hit the uninstall button next to the package you would like to remove from your project.

image

Another way of managing packages is thru a powershell like interface, using the keyboard. You can get to the console window by going to the View menu and selecting Other Windows –> Package Manager Console.

image

The following window will show up (the coloration might be different based on your personal color scheme settings in Visual Studio). 

image

You can manage your packages by using a few simple commands.

    • List-Package
    • Install-Package
    • Update-Package
    • Uninstall-Package

These do exactly what can be expected. The Install, Update and Uninstall need at least the name of the package as parameter. You can type help before each of these commands to get information on the other parameters.

image

One last thing. You can use the Tab key to auto-complete commands and even parameters.


Using Visual States in custom controls in Silverlight

You are reading an old version of my weblog. Please update your bookmarks to http://www.timmykokke.com

Intro

Visual States are an easy way to change the looks of your controls based on certain states. This state can be something like a mouse hover, some invalid state or any state you need in a control.

For this tutorial I chose a traffic light control that can be one of four states. Green, Orange, Red and Inconclusive (blinking orange). In the end I show you how to use behaviors on buttons to set the state of the traffic light. This makes the use of visual states perfectly suitable for use in MVVM projects.

Part 1 – Setting up the project

Start by creating a new Silverlight project in Visual Studio 2010 and add a new Item to the project by right clicking on the project in the Solution window and click Add –> New Item… or hit Ctrl+Shift+A.

image

Select the Silverlight Templated Control item template from the list of Silverlight templates

image

Add a folder named Themes to the Silverlight project. Add a ResourceDictionary to the project by using the Add->New Item… on the project folder and name this dictionary Generic.xaml. Add the following style to the dictionary:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:VsmDemo="clr-namespace:VsmDemo">
  <Style TargetType="VsmDemo:TrafficLight">
    <Style.Setters>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate/>
        </Setter.Value> 
      </Setter>
    </Style.Setters>
  </Style>
</ResourceDictionary>

Add a reference to the dictionary in App.xaml:

<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="Themes/generic.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
 </Application.Resources>

Build the solution to see I there aren’t any mistakes so far.

Part 2 – Drawing in Blend

Start Expression Blend and load the solution.

The template is still empty. To start editing the style for the TrafficLight control, go to the Resource pane, look for the generic.xaml entry, open it and click on the button on the right of the style entry.

image

To edit the template in the style, right click the style in the Objects and Timeline pane and select Edit Template –> Edit Current.

image

Now draw a traffic light like this.

image

If you don’t like/want/know how to draw the light, just copy-past the xaml below into the xaml editor. It’s basically just a border with a grid containing three ellipses.

<ControlTemplate>
  <Border d:DesignHeight="200.00" BorderBrush="#FFCACACA"
          BorderThickness="3"
          Background="#FF333333" CornerRadius="40"
          d:DesignWidth="110">
    <Grid >
      <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition Height="30"/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
      <ColumnDefinition Width="30"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="30"/>
      </Grid.ColumnDefinitions>
      <Ellipse x:Name="GreenLight"
               Grid.Column="1" Grid.Row="1"
               Fill="Black" Margin="2"
               Stretch="Uniform"/>
      <Ellipse x:Name="OrangeLight"
               Grid.Column="1" Grid.Row="2"
               Fill="Black" Margin="2" 
               Stretch="Uniform"/>
      <Ellipse x:Name="RedLight"
               Grid.Column="1" Grid.Row="3"
               Fill="Black" Margin="2" 
               Stretch="Uniform"/>
    </Grid>
  </Border>
</ControlTemplate>

Instantly the traffic light should show up in the designer.

Time to save your work again. Switch back to Visual Studio, and reload the files if you’re asked to.

Part 3 – Code… Finally

The selection of the different states will be based on an enum. Add a new enum to the Silverlight project.

public enum TrafficLightStates
{
    Inconclusive = 0,
    Green = 1,
    Orange = 2,
    Red = 3
}

The state of the traffic light will be stored in the control in a dependency property. The property will be set to TrafficLightStates.Green by default. A method must be called when the property changes to notify the state manager to change the state of the traffic light.

public TrafficLightStates State
{
    get { return (TrafficLightStates)GetValue(StateProperty); }
    set { SetValue(StateProperty, value); }
}

public static readonly DependencyProperty StateProperty =
    DependencyProperty.Register(
           "State", 
           typeof(TrafficLightStates),
           typeof(TrafficLight),
           new PropertyMetadata(TrafficLightStates.Green,
           OnLightStateChanged)
    );

To get the code to build, add a basic implementation of the OnLightStateChanged method. The OnLightStateChanged method calls the non-static SetState method. This way there will be only one method in which the visual state will be changed. The SetState method is empty for now.

private static void OnLightStateChanged(DependencyObject d,
                 DependencyPropertyChangedEventArgs e)
{
    ((TrafficLight)d).SetState();
}

private void SetState(){}

To make the four different visual states known to the application you’ll have to use the TemplateVisualState attribute. This attribute takes the name of the state and the name of the group the visual state belongs to. Add an instance of the TemplateVisualState attribute for each of the four states to the TrafficLight class.

[TemplateVisualState(Name = "Green", 
                     GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Orange", 
                     GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Red", 
                     GroupName = "TrafficLightStates")]
[TemplateVisualState(Name = "Inconclusive", 
                     GroupName = "TrafficLightStates")]

Now the states are named it is time to set the visual states based on the state of the traffic light. This is done by a simple switch block in the SetState method.

Changing the visual state of a control is done though a static method on the VisualStateManager class. Calling the GotoState method with the name will change the current visual state to a new one. Any transitions will be played automatically, if the useTransitions parameter is set to true. The GotoState method also needs a control of which the visual state needs to be sit. For this example we can just pass this to the method.

private void SetState()
{
    switch (State)
    {
        case TrafficLightStates.Green:
            VisualStateManager.GoToState(this, "Green", true);
            break;
        case TrafficLightStates.Orange:
            VisualStateManager.GoToState(this, "Orange", true);
            break;
        case TrafficLightStates.Red:
            VisualStateManager.GoToState(this, "Red", true);
            break;
        default:
            VisualStateManager.GoToState(this, "Inconclusive", true);
            break;
    }
}

The last thing that has to be done in code is setting the initial state by calling the SetState method once. You can override the OnApplyTemplate method for that.

public override void OnApplyTemplate()
{
    SetState();
    base.OnApplyTemplate();
}

Build to see if there are any mistakes made in the code… After that, switch back to Expression Blend.

Part 4 – Visual States

The last part of this tutorial will take place in Expression Blend. Every state of the traffic light has to have a corresponding visual state. The green light must be green, etc.

Go to the template of the TrafficLight control as shown before and open the States pane. Click on the Add State Group button on the right side of the pane.

image

Rename the VisualStateGroup group to TrafficLightStates.

image

Add four states to the group by clicking the Add state button right of the TrafficLightStates group header four times.

image

image

Rename the states to Green, Orange, Red and Inconclusive.

image

With the Green visual state and the GreenLight Ellipse selected, change the fill of the ellipse to green, like #FF2AFF00. Notice the red border around the drawing area indicating changes to the properties will be recorded. A small red light with a caption is shown at the top of the drawing area letting you know which state is recorded too, in this case “Green state recording is on”

image image
image image
image  

This process needs to be repeated for the orange and red ellipses too. In the example I’ve used #FFFFAA00 for the orange ellipse and #FFFF0000 for the red one.

The last state, Inconclusive, needs an animation so the orange light blinks. Select the Inconclusive visual state on the States pane. Show the animation timeline by clicking on the Show Timeline button on the Objects and Timeline pane.

image

Move the time slider to 0,5 seconds. Change the color to Orange (#FFFFAA00). Move the time slider to 1 second and change the color to black.

Click on the first key frame and set its easing function to cubic out.

image

Repeat the same for the second key frame. Set its easing function to cubic out also.

Select the storyboard by clicking on Inconclusive in the Objects and Timeline pane.

image

In the properties pane, set the Repeat Behavior of the storyboard to Forever.

image

That’s it for the visual states. Try compiling the application.

Part 5 – Testing the control

Open MainPage.xaml in Expression Blend.

Add the TrafficLight control to the LayoutRoot grid and give it a width of 110 and a height of 200.

To navigate to the four different states of the traffic light, add four buttons to the LayoutRoot grid and set their content to Green, Orange, Red and Inconclusive. Like this:

image

To change to State property of the traffic light you can use a ChangePropertyAction. You can find this in the Behaviors group on the Assets pane.

image

Drag-‘n-drop this action on the first button.

image

Select the Action in the Objects and Timeline pane. To set the TargetObject of action to the traffic light just click on the Artboard element picker and than on the traffic light.

image

Select State from the PropertyName combobox.

image

Select Green from the Value combobox.

image

Repeat the same process for the other three buttons. You can clone the behavior from element to element by selecting the behavior and drag-‘n-drop it to another element while holding down the Ctrl key.

Done!

Hit F5 to admire your work Smile 

You can download the source of the project here.

If you run into any issues or if you have comments or questions, please let me know. To be the first to know if there’s a new post on my blog, please subscribe to the RSS feed or follow me (@sorskoot) on twitter.



Custom Assets folder for Expression Blend

You are reading an old version of my weblog. Please update your bookmarks to http://www.timmykokke.com

In the projects I’m doing I often use controls from my own library or use control from third party vendors. I don’t like the process of doing this. Rather I would like to have the libraries available inside Expression Blend, like the controls that came with the Silverlight Toolkit or Blend itself.

One way is to add the custom assemblies containing the controls to one the folders in your Program Files containing the assemblies for the toolkit for example. Another and for more elegant way is to make Expression Blend look in an additional location in your UserProfile (c:/Users/SomeUser/…). The Expression Suite already has a folder in your My Documents, but not for assets.

I’ve create a .BAT file that adds a couple of folders to the Expression folder in the My Documents folder of the current user. Folders to store assemblies for .NET and Silverlight in various versions. A .REG file is used to add these locations to the windows registry.

After you have run both you’ll have to restart Blend to reread the registry and the folders. The assemblies placed in these folders are now available in Expression Blend. Your assemblies should show up in the Assets panel. By dragging and dropping them onto you pages the assemblies are automagically added to your project.

image

! Disclaimer: Note that by doing this you are making changes to the windows registry. Be sure to backup your system and the registry, and to save your work. I’m not taking any responsibility for you screwing up your system by not knowing what you are doing. Using the .reg and .bat files is at your on risk.

 

Download for 64 bit machines

Download for 32 bit machines



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 }=-



PivotViewer and MVVM

PivotViewer series

  1. Building your first PivotViewer application
  2. Runtime PivotViewer collection creation
  3. PivotViewer - Working with Facets
  4. Handling PivotViewer events
  5. PivotViewer - Custom actions
  6. PivotViewer and MVVM

Intro

The MVVM patterns is a commonly used pattern in Silverlight. Because of databinding MVVM suits perfectly for WPF and Silverlight. But use it only if appropriate. Often the pattern is used when it isn’t necessary. The usage of any pattern should be a helping tool, not an enforced law. Having that of my chest, lets look at the Silverlight PivotViewer control in combination with the MVVM pattern.

To make a long story short, the PivotViewer control isn’t suitable for use in MVVM out of the box. But there are a few ways you can make it work.

 

Wrapping the PivotViewer in a UserControl

The most simple way to get the control to work in an MVVM application is to place the control in a UserControl. You can use this control in your View and bind to properties you add to the UserControl. You’ll have to add dependency properties to the UserControl for each property you want to data bind to. The downside of wrapping the PivotViewer control in a UserControl is that you will have to add code to the CodeBehind of the UserControl.

 

For example a URL where the .CXML file is located. If this value changed you would like to load the collection. In the current version of the PivotViewer the only way to do this is to call the LoadCollection method on the PivotViewer control. By adding a dependency property to the UserControl you can bind a property of the ViewModel to this and have it load a collection on changes.

This dependency property  with its “OnChange” method might look something like this:

public string UrlSource{
    get { return (string)GetValue(UrlSourceProperty); }
    set { SetValue(UrlSourceProperty, value); }
}

public static readonly DependencyProperty UrlSourceProperty =
    DependencyProperty.Register("UrlSource",
                                typeof(string),
                                typeof(PivotViewerUserControl),
                                new PropertyMetadata(string.Empty,
                                                        OnUrlSourceChanged));
 
private static void OnUrlSourceChanged(DependencyObject d,
                                        DependencyPropertyChangedEventArgs e)
{
    if (!DesignerProperties.GetIsInDesignMode(d))
    {
        var userControl = (PivotViewerUserControl) d;
        userControl.Pivot.LoadCollection((string) e.NewValue,
                                             string.Empty);
    }
}

A logical next step would be to add a dependency property for the ViewerState parameter of the LoadCollection method and call it only when both are set or if the UserControl is Loaded.

To get notified when the selected item changed you can use an ICommand. Add a dependency property of type ICommand to the UserControl to be able to bind an implementation of the ICommand from the ViewModel to it. The property changed event on the PivotViewer control is handled. When the “CurrentItemId” property changes, thus the selected item changes, the event is executed. As a small extra feature the item is looked up on the PivotViewer and the whole PivotItem is passed as a parameter to the execute method.

public PivotViewerUserControl()
{
    InitializeComponent();
    Pivot.PropertyChanged += Pivot_PropertyChanged;
}

public ICommand SelectedItemChangedCommand
{
    get { return (ICommand)GetValue(SelectedItemChangedCommandProperty); }
    set { SetValue(SelectedItemChangedCommandProperty, value); }
}

public static readonly DependencyProperty SelectedItemChangedCommandProperty =
    DependencyProperty.Register("SelectedItemChangedCommand",
                                typeof(ICommand),
                                typeof(PivotViewerUserControl),
                                new PropertyMetadata(null));

private void Pivot_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "CurrentItemId")
    {
        if (this.Pivot.CurrentItemId == null)
        {
            // deselection
            this.SelectedItemChangedCommand.Execute(null);
        }
        else
        {
            // selection
            PivotItem item = Pivot.GetItem(Pivot.CurrentItemId);
            this.SelectedItemChangedCommand.Execute(item);
        }
    }
}

Extending the PivotViewer control itself

Another way to get to PivotViewer to work in an MVVM application is to extend the PivotViewer itself. The dependency properties you’ll be adding to the control are pretty much the same as the ones shown in the previous section, with the extend that you have better access to the guts of the PivotViewer control. This way you have access to the Custom Actions for example.

Where to go next

You could start by implementing all properties of the PivotViewer control as dependency properties and add a ICommands to event handlers. Maybe you can find constructions where you can extend the control with your own needs

I just hope that in the next version of the PivotViewer Microsoft did this boring work for us so we don’t have to.

I don’t have plans for a next tutorial on the PivotViewer, yet. If you have question or requests just let me know and I’ll see if I can help you. If you want to be the first to when a new tutorial is available, you can subscribe to the RSS-Feed or follow me on twitter.

Technorati Tags: ,

Share
 



PivotViewer – Custom Actions

PivotViewer series

  1. Building your first PivotViewer application
  2. Runtime PivotViewer collection creation
  3. PivotViewer - Working with Facets
  4. Handling PivotViewer events
  5. PivotViewer - Custom actions
  6. PivotViewer and MVVM

Intro

In this tutorial about the Silverlight PivotViewer control I would like to explain how to make use of Custom Actions. Small labels are placed on top of items in the viewer and clicking them will trigger an event.

The only downside of these actions is that they aren’t fully implemented. So you’ll have to extend the PivotViewer control yourself. If you haven’t worked with the PivotViewer before, you might want to have a look at the Building your first PivotViewer application tutorial I wrote earlier first. This tutorial continues on that.

Extending the control

Start by adding a new class to a Silverlight project and naming this PivotViewerEx. Make this class inherit from PivotViewer. Create an override of the GetCustomActionsForItem method. This method is called by the PivotViewer when it is in need of some custom actions. The id of the item the user is hovering is passed to this method. You can do some filtering of the actions based on that. In this example no filtering takes place and the whole collection of custom actions is returned.

The list of custom actions is defined as property of this class. It is instantiated by the constructor.

public class PivotViewerEx:PivotViewer
{
    public List<CustomAction> CustomActions { get; set; }
 
    public PivotViewerEx()
    {
        CustomActions=new List<CustomAction>();
    }
 
    protected override List<CustomAction> GetCustomActionsForItem(string itemId)
    {
        return CustomActions;
    }
}

 

 

Using the control

The extended PivotViewer control works in the same way as the original. It can be added to the XAML like below. The event that handles the clicks on the actions is added too.

<UserControl x:Class="PivotViewerCustomActions.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:PivotViewerCustomActions="clr-namespace:PivotViewerCustomActions" 
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
 
    <Grid x:Name="LayoutRoot" Background="White">
        <PivotViewerCustomActions:PivotViewerEx x:Name="Pivot" 
               ItemActionExecuted="CustomActionClicked"/>
    </Grid>
</UserControl>

 

In the code behind, in the constructor of the page, the custom actions itself are added to the PivotViewer. The constructor of the CustomAction class takes four parameters:

  • Name => is the text shown in the PivotViewer
  • Icon => a URI to an image to show next to the text. You can use NULL to omit an image
  • ToolTip => some text that is shown when the user hovers the mouse over the CustomAction
  • Id => a unique ID to identify the action
public MainPage()
{
    InitializeComponent();
 
    Pivot.CustomActions.Add(
        new CustomAction("Add to cart",
            new Uri("http://localhost:49000/112_Plus_Green_32x32_72.png"),
            "Add to cart","Add"));
   
    Pivot.CustomActions.Add(
        new CustomAction("Details",
                            new Uri("http://localhost:49000/Info.png"), 
                            "Details","Details"));
    
    Pivot.LoadCollection("http://localhost:49000/ElectronicsPivot.cxml",
        string.Empty);
}

Handling the event

When the user clicks on the actions the CustomActionClicked event is fired. The event gets an instance of the ItemActionEventArgs class as event arguments. This class contains two properties. ItemId contains the the ID of the item the action was placed over. You can get the actual item by calling the GetItem method on the PivotViewer control with this ID.

The second property of the ItemActionEventArgs class is CustomActionId. This is the ID of the custom action that was clicked.

In the example below one of two a message boxes is shown depending on the action clicked. It won’t be hard to extend this further to your needs. 

private void CustomActionClicked(object sender, ItemActionEventArgs e)
{
    PivotItem item = Pivot.GetItem(e.ItemId);
    
    if (e.CustomActionId == "Add")
    {
        MessageBox.Show(string.Format("Add {0} to Cart", item.Name));
    
 
    if (e.CustomActionId == "Details")
    {
        MessageBox.Show(string.Format("Show details of {0}", item.Name));
    }        
}

 

Wrap-up

CustomActions provide a great way to add some extra functionality to the PivotViewer control. Too bad they aren’t fully implemented (yet?). The simple method shown in this tutorial uses code behind to add the actions. It would be great to be able to add these actions in XAML one day.

The next tutorial will be about using the Silverlight PivotViewer control in an MVVM application. If you want to be the first to know when it is available, you can subscribe to the RSS-Feed or follow me on twitter.

Technorati Tags: ,

Share
 


 



Handling PivotViewer events

PivotViewer series

  1. Building your first PivotViewer application
  2. Runtime PivotViewer collection creation
  3. PivotViewer - Working with Facets
  4. Handling PivotViewer events
  5. PivotViewer - Custom actions
  6. PivotViewer and MVVM

Intro

Today I would like to go into a little detail about the events used in the PivotViewer control for Silverlight. If you haven’t worked with the PivotViewer yet you might want to read the getting started tutorial I wrote earlier first.

CollectionLoadingCompleted

The CollectionLoadingCompleted event is fired when loading of the collection is completed. 

CollectionLoadingFailed

The CollectionLoadingFailed event is raised when an error occurs when loading a collection. The event uses gets an instance of the CollectionErrorEventArgs class when it is fired. This class contains two properties.

The first is ErrorCode. This property is of the enum type CollectionError and contains two values: DownloadError and ParsingError.

ErrorCode equals DownloadError when there was an error downloading the collection. For example if the URL used in the LoadCollection method is wrong. The ErrorCode contains the ParsingError value when there is an issue with the .CXML file which prevents it from being parsed. For example a typing error in the .CXML.

The second property used in the CollectionErrorEventArgs class is Exception. This property contains the exception thrown by he PivotViewer control. This exception can provide very useful information when building runtime collections.
 

ItemDoubleClicked

This event is fired when an item in the PivotViewer is double clicked. The event is given a ItemEventArgs object. The ItemEventArgs class contains 1 property, ItemId. This string contains the ID of the items that is clicked. You can use this ID to get the whole item by calling the GetItem method on the PivotViewer control.


private void Pivot_ItemDoubleClicked(object sender, ItemEventArgs e)
{
    PivotItem item = Pivot.GetItem(e.ItemId);
 
    // insert something useful to do with the item here
    // like showing a popup with more info.
}

 

 

 

LinkClicked

When the end-user click on a facet of the link type this event is fired by the PivotViewer control. The URL is passed to the event through the LinkEventArgs. The navigation itself isn’t performed by the PivotViewer. You’ll have to handle that yourself. The code below shows an example of that. It checks if the URL that is clicked ends with .CXML. In that case the URL is used to load a new collection. Otherwise the user will be directed to the target URL.

private void Pivot_LinkClicked(object sender, LinkEventArgs e)
{
    Uri targetUrl = e.Link;
    if (targetUrl.LocalPath.EndsWith(".cxml", 
        StringComparison.InvariantCultureIgnoreCase))
    {
        //If the link is to CXML, show it in this PivotViewer.
        Pivot.LoadCollection(targetUrl.AbsoluteUri, string.Empty);
    }
    else
    {
        //Otherwise open the URL in a new window
        HtmlPage.Window.Navigate(targetUrl, "_blank");
    }
}

 

 

 

 

ItemExecutedEvent

The ItemExecutedEvent is raised when the end-user clicks on a Custom Action. Support for this isn’t fully implemented in this version of the PivotViewer control. In the next tutorial I’ll show you how to use custom actions and how they are handled using this event.

Wrap-up

There aren’t that many events in the PiverViewer control. But it’s good to know which ones are there and how to use them.

The next tutorial will be about Custom Actions. To be the first to know when it is released you can subscribe to the RSS-feed or follow me on twitter.

 

 

Technorati Tags: ,

Share
 


 

kick it on DotNetKicks.com
 

Shout it
 



PivotViewer – Working with Facets

PivotViewer series

  1. Building your first PivotViewer application
  2. Runtime PivotViewer collection creation
  3. PivotViewer - Working with Facets
  4. Handling PivotViewer events
  5. PivotViewer - Custom actions
  6. PivotViewer and MVVM

Intro

In this next tutorial about the Silverlight PivotViewer control I would like to give a little more depth on Facets. What are facets, and how are they used in runtime generation of collections using the PivotServerTools library.

This tutorial continues on techniques from last tutorial about runtime collection creation. If you are just getting started using the PivotViewer control, you might want to have a look at the Getting Started Tutorial first. This tutorial is centered around the methods build in the last tutorial: MakeCollection and MakeItem.

 

Facets

Facets are basically the properties on the PivotViewer that allow the visitor to sort and filter. Facets are also shown when viewing the details of an item.

PivotViewerFacetsOverview

Facets are added to the collections by calling the Collection.AddItem() method. This method takes a couple of parameters. The first is the Name of the item being added. The second is a URL. This can be used to navigate to more details about the item for example. This URL is used when clicking on the Name of the item in the details panel. Then there’s the Description of the item. This text is shown on the details panel. The fourth parameter is the image shown in the DeepZoom part of the control. The ItemImage type from the PivotServerTools. Its constructor is used, to which a URL to the image is given. All parameters after that, from the fifth on are Facets. You can add as many as you need. A call to AddItem might look something like this:

collection.AddItem(
        id,
        url,
        description,
        new ItemImage(new Uri(image)),
        new Facet("String value", FacetType.Text, id),
        new Facet("Integer Value", FacetType.Number, intValue),
        new Facet("Double Value", FacetType.Number, doubleValue),
        new Facet("Date value",FacetType.DateTime,date),
        new Facet("Url Value",FacetType.Link, new FacetHyperlink("Url Value", urlValue)),
        new Facet("Names", names),
        new Facet("FormattedValue",formattedValue)
        );

 

 

 

 

 

Facets are grouped in Facet Categories. Every item in the collection can contain one or more facet categories and every category can contain one or more facets. Facet categories are created when a they are used for the first time while adding items to the collection. 

 FacetDetails The PivotServerTools library is used to generate the .CXML. It uses 4 types of facets categories:Text, Number, DateTime and Link. The type of facet category determines how facets are displayed in the PivotViewer control.  Each facet in the category must be of this type.

Text:

The text type is used to display anything of type string. If the type is omitted and the type can’t be determined automatically the Text type is defaulted to.

To create a facet of type text you can use its constructor with a category name, the type of facet and its tag. For example:

Facet stringFacet = new Facet("Names", FacetType.Text, name);

 

 

 

 

 

This might look something like this in the PivotViewer control.

image

Number:

This facet type is used to display numbers. It allows the end-user to make selections on ranges of this tag. This tag value can also be formatted which I’ll explain later.

Again, to create a facet of this type, use its constructor and pass in a different FacetType this time:

 Facet integerFacet = new Facet("Integer Value", FacetType.Number, intValue);
 Facet doubleFacet = new Facet("Double Value", FacetType.Number, doubleValue);

image

DateTime:

Dates are displayed like in the image below. You can select a date by era, the actual value or select a custom range.

The date facets are added the same way as numbers or text, but with a different FacetType.

Facet dateFacet = new Facet("Date value",FacetType.DateTime, date);
image 

Link:

Hyperlinks are not shown in the filter list. Only the name given to the URL is shown in the details list.  Clicking on a link does not navigate by default. You’ll have to implement the navigate yourself. An event is fired when an item on the details panel is clicked though.

To create a facet of type link you can use its constructor again. Only the third parameter is different this time. It takes a value of type FacetHyperLink. The type uses a description and a URL together. In the code below both are passed into the constructor of FacetHyperLink. Both parameters are strings.  

 

 

 

Facet linkFacet = new Facet("Url Value", FacetType.Link, 
                            new FacetHyperlink("Displayed Name", urlValue));

 

One last thing to notices about adding items to the collection. As I mentioned earlier, every facet category can be used zero or more times. The constructor of Facets takes one or more values for a value for each tag. You could, for example, add an array of strings to a category at once just by passing that array to the constructor. All values will be shown in that category on the details panel.

string[] myNames = {"Timmy Kokke", "Sorskoot"};
Facet namesFacet = new Facet("My Names",FacetType.Text, names );

 

More on categories

After the items are added to the collection you can fine-tune the categories a little further. Often it is necessary to make facet categories visible in only the details panel or enable filtering for a particular category but disable text search on them. The Collection class has a method to set these properties.

The SetFacetDisplay method takes the name of the category and 3 booleans.  The first of the three booleans indicated whether or not the category is shown in the list of filters. The second enables or disables the category showing up in de info panel. When the last is set to false the category is excluded from the text search.

Here are a few examples.

collection.SetFacetDisplay("Integer Value", true, false, false);
collection.SetFacetDisplay("Double Value", false, true, false);
collection.SetFacetDisplay("Names", true, true, false);

The Integer Value category is shown in the list of filters, but hidden from the info panel and the text search. The Double Value category is hidden from the filters and the text search, but is visible on the info panel. The Names category is visible in both filters and info panel, but isn’t used for text search.

The Collection class has one other method of interest concerning facets. The SetFacetFormat is used to set format of a category in which it is displayed. It uses standard .NET string formatting. For example, to display a double as a floating point with 3 decimals you can use the following code:

collection.SetFacetFormat("FormattedValue", "F3");

 

 

 

Wrap-up

The code that goes along with this tutorial can be downloaded here. The next tutorial will be about the events of the PivotViewer control. To be the first to know when it is released you can subscribe to the RSS-feed or follow me on twitter.

Technorati Tags: ,

Share


 

kick it on DotNetKicks.com
 

Shout it