Testing the SH WP ApplicationBar in an Multiselectlist MVVM scenario

If you’re developing for Windows Phone 7 and are using MVVM you’re probably familiar with the problem that you cannot bind the out of the box ApplicationBar because it is not a silverlight control. Since the early days of WP7 there are lots of solutions and workarounds to work with the application bar but most of them do have some (minor) downsides in using them. The application bar solutions that are used the most are probably the BindableApplicationBar from PhoneFX, another BindableApplicationBar or AppBarUtils.

Up untill now I was using the PhoneFX BindableApplicationBar but I really disliked the problem that you can’t bind the visibility property of the ApplicationBarButtons to hide or show them when you need them. A common example where you use this is in a Scenario with a MultiSelectList on a page where you want to be able to hide the “Remove” button as long as you didn’t select an item yet and hide the “Select” button when you are already in the selection mode. This week I was reading a blogpost on Windows Phone Geek about the AdvancedApplicationBar and I read that this new ApplicationBar solution did support binding the Visibility of ApplicationBarButtons so it was time to put this one to the test.

In this post I’ll walk you through my the code I produced to get a nice MultiSelectList control (from the silverlight wp7 toolkit ) working with the applicationbar without writing any codebehind. I used MVVM light for this sample so an empty MVVM light project with references added to the Silverlight Toolkit and the SH WP ApplicationBar will be my starting point.

The idea is to build an application showing a MultiSelectList with some messages that you can select and delete by using the ApplicationBarButtons just as the build in Mail application does.

Lets first start of building some of the plumbing to get this application going. We’ll create a Message Class that is going to be our Class containing the information for each message. We’ll keep this Class plain and simple:

   1: public class Message

   2: {

   3:     public string Sender { get; set; }

   4:     public DateTime Date { get; set; }

   5:     public string Content { get; set; }

   6: }

We’ll also need a property in the ViewModel to expose a list of these Messages which we can fill with dummy data and that can be bound in the MultiSelectList. We’ll create a property in the ViewModel called Messages and will fill these for this small example in the constructor of the MainViewModel.

   1: /// <summary>

   2: /// Initializes a new instance of the MainViewModel class.

   3: /// </summary>

   4: public MainViewModel()

   5: {

   6:     for (int i = 0; i < 10; i++)

   7:     {

   8:         Message m = new Message();

   9:         m.Sender = "Sender " + i.ToString();

  10:         m.Date = DateTime.Now.AddHours(i);

  11:         m.Content = "This is a sample message " + i.ToString();

  12:         Messages.Add(m);

  13:     }

  14: }

  15:  

  16: /// <summary>

  17: /// The <see cref="Messages" /> property's name.

  18: /// </summary>

  19: public const string MessagesPropertyName = "Messages";

  20:  

  21: private ObservableCollection<Message> _messages = null;

  22:  

  23: /// <summary>

  24: /// Sets and gets the Messages property.

  25: /// Changes to that property's value raise the PropertyChanged event. 

  26: /// </summary>

  27: public ObservableCollection<Message> Messages

  28: {

  29:     get

  30:     {

  31:         return _messages;

  32:     }

  33:  

  34:     set

  35:     {

  36:         if (_messages == value)

  37:         {

  38:             return;

  39:         }

  40:  

  41:         _messages = value;

  42:         RaisePropertyChanged(MessagesPropertyName);

  43:     }

  44: }

Now the data is there it’s time to create the UI. One of the best parts of using MVVM is creating the UI in Expression Blend so lets use that. We’ll add a MultiSelectList Control to the page (it’s a control that comes in the silverlight toolkit for wp7) and bind the itemsource to the Messages property. We’ll also add the AdvancedApplicationBar from the SH WP library to the page and create 2 buttons to be used on the ApplicationBar, a select button and a delete button. Set the size of the MultiSelectList to Autosize –> full and make sure the AdvancedApplicationBar control is located in the Layoutroot. Set the text of the 2 ApplicationBarButtons to Select and Remove and also select an image for the buttons.

multiselectlist

When you rebuild now you’ll see 10 lines of code in the multiselect list. Change the ItemTemplate for the MultiSelectList by creating an empty template and adding 3 textboxes to them binding them to our 3 fields in our Message Class: Sender, Date and Content. Give all of them a pretty style and we’re ready to go on.

itemtemplate

Your Xaml for the contentgrid should look like this

   1: <Grid x:Name="ContentGrid"

   2:       Grid.Row="1" Height="537" VerticalAlignment="Top">

   3:     <toolkit:MultiselectList ItemsSource="{Binding Messages}" ItemTemplate="{StaticResource MessageTemplate}"/>

   4:     <Sh:AdvancedApplicationBar>

   5:         <Sh:AdvancedApplicationBarIconButton Text="Select" IconUri="/Images/ApplicationBar.Select.png"/>

   6:         <Sh:AdvancedApplicationBarIconButton Text="Remove" IconUri="/Images/ApplicationBar.Delete.png"/>

   7:     </Sh:AdvancedApplicationBar>

   8: </Grid>

The Xaml for the ItemTemplate looks like this

   1: <phone:PhoneApplicationPage.Resources>

   2:     <DataTemplate x:Key="MessageTemplate">

   3:         <StackPanel>

   4:             <TextBlock TextWrapping="Wrap" Text="{Binding Sender}" Style="{StaticResource PhoneTextLargeStyle}"/>

   5:             <TextBlock TextWrapping="Wrap" Text="{Binding Date}" Style="{StaticResource PhoneTextAccentStyle}"/>

   6:             <TextBlock TextWrapping="Wrap" Text="{Binding Content}" Style="{StaticResource PhoneTextNormalStyle}"/>

   7:         </StackPanel>

   8:     </DataTemplate>

   9: </phone:PhoneApplicationPage.Resources>

When we run our application now the output should be similar to this. You can tap on the left side of the screen to select items in the list just like you can in the build in mail application.

messages1 messages2

It is pretty weird to have the Remove button visible when you’re not in selection mode of the MultiSelectList and the same thing goes for the Select button that’s still visible when the MultiSelectList is in selectionMode. To fix this we’ll bind the Visibility property of these ApplicationBarButtons to a boolean property that is also 2 way bound to the IsSelectionEnabled property of the MultiSelectList.

To do this we first need to add a boolean property to the ViewModel called IsInSelectionMode

   1: /// <summary>

   2: /// The <see cref="IsInSelectionMode" /> property's name.

   3: /// </summary>

   4: public const string IsInSelectionModePropertyName = "IsInSelectionMode";

   5:  

   6: private bool _isInSelectionMode = false;

   7:  

   8: /// <summary>

   9: /// Sets and gets the IsInSelectionMode property.

  10: /// Changes to that property's value raise the PropertyChanged event. 

  11: /// </summary>

  12: public bool IsInSelectionMode

  13: {

  14:     get

  15:     {

  16:         return _isInSelectionMode;

  17:     }

  18:  

  19:     set

  20:     {

  21:         if (_isInSelectionMode == value)

  22:         {

  23:             return;

  24:         }

  25:  

  26:         _isInSelectionMode = value;

  27:         RaisePropertyChanged(IsInSelectionModePropertyName);

  28:     }

  29: }

When we have this property we can bind the property to the IsSelectionEnabled property of the MultiSelectList. For some reason this can’t be done in Blend since the DataBinding button is greyed out but coding it in Xaml does work. The binding looks like this in Xaml

   1: <toolkit:MultiselectList ItemsSource="{Binding Messages}" ItemTemplate="{StaticResource MessageTemplate}" IsSelectionEnabled="{Binding IsInSelectionMode, Mode=TwoWay}"/>

The Visibility property of the ApplicationBarButtons isn’t a boolean type so we’ll need a converter to convert the boolean to a Visibility Property. I’m using 2 converters here. 1 is converting the boolean value True to Visibility.Visible and the other converter is also an inverter and is converting True to Visibility.Collapsed.

   1: /// <summary>

   2: /// Converts a boolean to Visibililty

   3: /// </summary>

   4: ///[ValueConversion(typeof(bool), typeof(Visibility))]

   5: public class BooleanToVisibilityConverter : IValueConverter

   6: {

   7:     #region IValueConverter Members

   8:  

   9:     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  10:     {

  11:         Visibility result = Visibility.Collapsed;

  12:  

  13:         bool val;

  14:  

  15:         if (value != null &&

  16:             bool.TryParse(value.ToString(), out val))

  17:         {

  18:             result = val ? Visibility.Visible : Visibility.Collapsed;

  19:         }

  20:  

  21:         return result;

  22:     }

  23:  

  24:     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  25:     {

  26:         //You can't convert back

  27:         return null;

  28:     }

  29:  

  30:     #endregion

  31: }

  32:  

  33:  

  34: /// <summary>

  35: /// Converts a boolean to Collapsed Visibililty

  36: /// </summary>

  37: ///[ValueConversion(typeof(bool), typeof(Visibility))]

  38: public class BooleanInverterToVisibilityConverter : IValueConverter

  39: {

  40:     #region IValueConverter Members

  41:  

  42:     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  43:         {

  44:             Visibility result = Visibility.Collapsed;

  45:  

  46:             bool val;

  47:  

  48:             if (value != null &&

  49:                 bool.TryParse(value.ToString(), out val))

  50:             {

  51:                 result = val ? Visibility.Collapsed : Visibility.Visible;

  52:             }

  53:  

  54:             return result;

  55:         }

  56:  

  57:         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  58:         {

  59:             //You can't convert back

  60:             return null;

  61:         }

  62:  

  63:         #endregion

  64:     }

Lets Bind the boolean value using the converter to the ApplicationBarIcons. Your Xaml should look like this:

   1: <Sh:AdvancedApplicationBarIconButton Text="Select" IconUri="/Images/ApplicationBar.Select.png" Visibility="{Binding IsInSelectionMode, Converter={StaticResource BooleanInverterToVisibilityConverter}}"/>

   2: <Sh:AdvancedApplicationBarIconButton Text="Remove" IconUri="/Images/ApplicationBar.Delete.png" Visibility="{Binding IsInSelectionMode, Converter={StaticResource BooleanToVisibilityConverter}}"/>

If you run the application again you should be able to see the icons showing up and hiding at the correct times now.

To finish this sample and blogpost up we want the Select button to put the MultiSelectMode in selection mode and the remove button should remove the selected items. Lets start with the Select button. We’ll create a RelayCommand in the viewmodel that puts the MultiSelectList into selectionMode.

   1: private RelayCommand _messageListToSelectModeCommand;

   2:  

   3: /// <summary>

   4: /// Gets the MessageListToSelectModeCommand.

   5: /// </summary>

   6: public RelayCommand MessageListToSelectModeCommand

   7: {

   8:     get

   9:     {

  10:         return _messageListToSelectModeCommand

  11:             ?? (_messageListToSelectModeCommand = new RelayCommand(

  12:                 () =>

  13:                 {

  14:                     IsInSelectionMode = true;

  15:                 }));

  16:     }

  17: }

On the Select ApplicationBarButton we’ll add an EventToCommand behavior that will trigger this RelayCommand. I did this in Blend but the Xaml that is created will look like this:

   1: <Sh:AdvancedApplicationBarIconButton Text="Select" IconUri="/Images/ApplicationBar.Select.png" Visibility="{Binding IsInSelectionMode, Converter={StaticResource BooleanInverterToVisibilityConverter}}">

   2:     <i:Interaction.Triggers>

   3:         <i:EventTrigger EventName="Click">

   4:             <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding MessageListToSelectModeCommand, Mode=OneWay}"/>

   5:         </i:EventTrigger>

   6:     </i:Interaction.Triggers>

   7: </Sh:AdvancedApplicationBarIconButton>

Running the application again will show us that using the select button puts the MultiSelectList in selectionmode so that part is finished. It only took 1 line of code in the relaycommand.

Removing the items is a bit more work since you can’t do a 2 way binding on the SelectedItems of a MultiSelectList because it is not a dependency property. The best way to get this working is setting up a property in the Viewmodel that is going to contain the selected items and update this list every time the selectionchanged event is fired by another EventToCommandBehavior that triggers a RelayCommand called SelectedMessagesChangedCommand. The SelectedMessagesChangedCommand will update the ViewModel property that will later be used to delete the items.

   1: /// <summary>

   2: /// The <see cref="SelectedMessages" /> property's name.

   3: /// </summary>

   4: public const string SelectedMessagesPropertyName = "SelectedMessages";

   5:  

   6: private ObservableCollection<Message> _selectedMessages = null;

   7:  

   8: /// <summary>

   9: /// Sets and gets the SelectedMessages property.

  10: /// Changes to that property's value raise the PropertyChanged event. 

  11: /// </summary>

  12: public ObservableCollection<Message> SelectedMessages

  13: {

  14:     get

  15:     {

  16:         return _selectedMessages;

  17:     }

  18:  

  19:     set

  20:     {

  21:         if (_selectedMessages == value)

  22:         {

  23:             return;

  24:         }

  25:  

  26:         _selectedMessages = value;

  27:         RaisePropertyChanged(SelectedMessagesPropertyName);

  28:     }

  29: }

  30:  

  31: private RelayCommand<IList> _selectedMessagesChangedCommand;

  32:  

  33: /// <summary>

  34: /// Gets the SelectedMessagesChangedCommand.

  35: /// </summary>

  36: public RelayCommand<IList> SelectedMessagesChangedCommand

  37: {

  38:     get

  39:     {

  40:         return _selectedMessagesChangedCommand

  41:             ?? (_selectedMessagesChangedCommand = new RelayCommand<IList>(ExecuteSelectedMessagesChangedCommand));

  42:     }

  43: }

  44:  

  45: private void ExecuteSelectedMessagesChangedCommand(IList parameter)

  46: {

  47:  

  48:     SelectedMessages = new ObservableCollection<Message>(parameter.Cast<Message>());

  49: }

Make sure the EventToCommand behavior is passing the SelectedItems as a command property. This can all be done in Blend but here is the Xaml that should be generated by Blend

   1: <i:Interaction.Triggers>

   2:     <i:EventTrigger EventName="SelectionChanged">

   3:         <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding SelectedMessagesChangedCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItems, ElementName=multiselectList}"/>

   4:     </i:EventTrigger>

   5: </i:Interaction.Triggers>

Now we have the selected messages in our viewmodel we can use our last RelayCommand called DeleteSelectedMessagesCommand to remove the selected messages.

   1: private RelayCommand _deleteSelectedMessagesCommand;

   2:  

   3: /// <summary>

   4: /// Gets the DeleteSelectedMessagesCommand.

   5: /// </summary>

   6: public RelayCommand DeleteSelectedMessagesCommand

   7: {

   8:     get

   9:     {

  10:         return _deleteSelectedMessagesCommand

  11:             ?? (_deleteSelectedMessagesCommand = new RelayCommand(

  12:                 () =>

  13:                 {

  14:                     foreach (Message m in SelectedMessages)

  15:                     {

  16:                         Messages.Remove(m);

  17:                     }

  18:                 }));

  19:     }

  20: }

This needs to be triggered again from an EventToCommand behavior attached to the remove ApplicationBarButton.

   1: <i:Interaction.Triggers>

   2:     <i:EventTrigger EventName="Click">

   3:         <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding DeleteSelectedMessagesCommand, Mode=OneWay}"/>

   4:     </i:EventTrigger>

   5: </i:Interaction.Triggers>

We can run our application again and when you press the remove button the selected items should be removed.

This sample proves the SH WP AdvancedApplicationBar is working pretty good and it proves it has features that I didn’t get to work in the BindableApplicationBar for example the Visibility of the ApplicationBarButtons. I think I’m going to use this ApplicationBar more often in my projects.

Hopefully this sample is usefull for you to see what the SH WP ApplicationBar is up to or just to get an impression on how to work with a bit more advanced ApplicationBar scenario’s using MVVM.

Sourcecode for the sample project can be downloaded here

Happy Coding

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Creating dynamic Windows Phone 7 live tile images client side

One of the best parts of windows phone that makes Windows Phone stand out are the live tiles. Microsoft enables you to do a few out of the box customizations to the live tiles but  when you want to go all out most people think you’ll need to generate the images on a server using ASP.NET and then send them to the application as a notification. This is not always the case, you can also create custom tiles client side running on your phone to show custom messages or imitate the outlook tile for example with a number of how many unread messages you have.

First lets sum up what you can do by default and after that we’ll go into going beyond this and creating even better live tiles by adding multiple images or multiple texts to a live tile using the colors and fonts of your choice.

By default you can set the following properties on a live tile

  • Title (shown in the bottom left)
  • Count (black circle with a number between 1 and 99)
  • BackGroundImage (image to show on your tile)
  • BackTitle (shown in the bottom left on the backside of the tile)
  • BackContent (piece of text shown on the backside of the tile)
  • BackBackGroundImage (Image on the backside of the tile)

Ok this is pretty cool but what if we want to make something like Runkeeper does in their app as shown in the following picture:runkeeper live tile

So how do we generate such image on the client side in Silverlight? The trick behind all this is that you can render a user control as a WriteableBitmap and store this image in the isolated storage of your phone so you can use it as the tile BackGroundImage. The final working codesample is linked at the bottom of this post but I’ll show all code to build this example in this blogpost.

We start of creating a new Silverlight for Windows Phone project. Normally I would use MVVM but for this example I want to make it as simple as possible to focus on the tile part.

We’ll create a new UserControl called “TileControl” which is going to be used as our live tile and a “TileData” class to be used for containing the data we’ll be showing on the  live tile.

   1: public class TileData

   2: {

   3:     public string Text1 { get; set; }

   4:     public string Text2 { get; set; }

   5:     public string ImageSource { get; set; }

   6: }

Create the TileControl, set it to 173 by 173pixels and set the background to use PhoneAccentBrush so the live tile has the color the user has selected. Lets make our designers happy and open up the TileControl in expression blend so our designers (or if you are a devigner you!) can design our live tile with dynamic data.

Add a few text boxes and a image to the control so you have something like this:

   1: <Grid x:Name="LayoutRoot" Width="173" Height="173" Background="{StaticResource PhoneAccentBrush}">

   2:     <TextBlock Height="55" Margin="4,4,3,0" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="White" FontSize="24"/>

   3:     <TextBlock Margin="0,64,-17,-3" TextWrapping="Wrap" FontSize="64" HorizontalAlignment="Right" Width="70" Foreground="White"/>

   4:     <Image Margin="6,55,0,13" Width="100" HorizontalAlignment="Left"/>

   5: </Grid>

In the Data window click the icon “Create sample data from class” and select the TileData class.

create sample data

Edit the sample data so we have some nice data to show. I used the following data:

   1: <CustomLiveTileExample:TileData xmlns:CustomLiveTileExample="clr-namespace:CustomLiveTileExample" 

   2: ImageSource="ApplicationIcon.png" 

   3: Text1="The first Text"

   4: Text2="9"/>

Now drag the fields from the test data window to the text and image control to bind them. After this your XAML should look like this and the design surface should already show a nice live tile with an image and 2 texts. In our code we’ll databind this control to a programmatically filled TileData object.

   1: <Grid x:Name="LayoutRoot" Width="137" Height="137" Background="{StaticResource PhoneAccentBrush}" d:DataContext="{d:DesignData /SampleData/TileDataSampleData.xaml}">

   2:     <TextBlock Height="55" Margin="4,4,3,0" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="White" FontSize="21.333" Text="{Binding Text1}"/>

   3:     <TextBlock Margin="0,50,-10,11" TextWrapping="Wrap" FontSize="48" HorizontalAlignment="Right" Width="70" Foreground="White" Text="{Binding Text2}"/>

   4:     <Image Margin="12,51,65,17" Width="60" Source="{Binding ImageSource}"/>

   5: </Grid>

blend tile

The live tile is ready so lets head back to the main page of our application and add the logic to set the live tile. To trigger the creation of the live tile I’ve added a button on the page and attached a click event. in the button1_Click method I’ll add all code needed to create the live tile.

   1: private void button1_Click(object sender, RoutedEventArgs e)

   2:         {

   3:             TileControl frontTile = new TileControl();

   4:             TileData tileData = new TileData() { ImageSource = "/ApplicationIcon.png", Text1 = "The first text", Text2 = "8" };

   5:             frontTile.DataContext = tileData;

   6:  

   7:             frontTile.Measure(new Size(173, 173));

   8:             frontTile.Arrange(new Rect(0, 0, 173, 173));

   9:             var bmp = new WriteableBitmap(173, 173);

  10:             bmp.Render(frontTile, null);

  11:             bmp.Invalidate();

  12:  

  13:             var isf = IsolatedStorageFile.GetUserStoreForApplication();

  14:             var filename = "/Shared/ShellContent/tile.jpg";

  15:  

  16:             if (!isf.DirectoryExists("/Shared/ShellContent"))

  17:             {

  18:                 isf.CreateDirectory("/Shared/ShellContent");

  19:             }

  20:  

  21:             using (var stream = isf.OpenFile(filename, System.IO.FileMode.OpenOrCreate))

  22:             {

  23:                 bmp.SaveJpeg(stream, 173, 173, 0, 100);

  24:             }

  25:  

  26:             var data = new StandardTileData

  27:             {

  28:                 BackgroundImage = new Uri("isostore:" + filename, UriKind.Absolute)

  29:             };

  30:  

  31:             ShellTile.Create(new Uri("/MainPage.xaml", UriKind.Relative), data);

  32:         }

First we’ll create a TileControl object called frontTile, then we’ll fill it with our tileData by creating a TileData object and setting the DataContext to tileData. After this we’ll create a WriteableBitmap and set it to 173 by 173 pixels. Well use the Render method to render the usercontrol as a bitmap.

After that we’ll check if the directory in the isolated storage exists and if it doesn’t we’ll create it. After that we’ll open the tile file and use the SaveJpeg method to save the WritableBitmap as a .jpg file (bit of a shame you can’t do png that’s why we’ve set the background color to the PhoneAccentColor). after saving the image the only thing we need to do is Call Create on the ShellTile and we’re done.

Lets run the app, press the button and there it is, our dynamically created livetile.

app1    app2

Download Sample project:

Happy coding!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Tutorial: How to use the Silverlight Toolkit transitions without writing XAML by using the Toolkit behavior extensions

In my last post I announced the new Codeplex project I’ve started called the Windows Phone Silverlight toolkit behavior extensions. In this post I’ll explain how to use the behaviors in this project in Expression Blend to create beautiful page transitions supplied by the Silverlight Toolkit for windows Phone without writing any code or XAML!

how to get started

Download the silverlight toolkit for windows phone and the Windows Phone Silverlight toolkit behavior extensions and install both libraries on your system.

After the installation start Expression Blend and create a new Windows Phone 7 Project.

In the projects window right click “References” and select “Add Reference”add reference

Select the Microsoft.Phone.Controls.Toolkit.dll file and press “Open”add reference 2

Select the PhoneToolkit.Extensions.Behaviors.dll and press “Open”add reference 3

You should now have Microsoft.Phone.Controls.Toolkit.dll and PhoneToolkit.Extensions.Behaviors.dll in your References list.add reference 4

Before the transition behaviors work you will have to change 1 thing in the code because that is just how the Silverlight Toolkit Transitions work. so open App.xaml.cs and locate the following Class: “PhoneApplicationFrame”PhoneApplicationFrame

And Change it to “TransitionFrame”TransitionFrame

Build the project and after building the new behaviors will be added to the Assets window.

behavior

You can drag and drop the new behaviors on your PhoneApplicationPage to enable the tilt effect or enable a page transition. In the Example below I’ve added the EnableTiltEffectBehavior to enable the tilting effect on every clickable usercontrol and I’ve added a TransitionTurnstileInBehavior to show a turnstile animation on entering the page and a TransitionTurnstileOutBehavior to show a turnstile animation on leaving the page.

objectsandtimeline

The transition behaviors have 2 properties where you can set the animation for forward and backward transitions. by default the most common animations are selected.properties

To test if everything is working drag a button on the content grid and add a second page to your application. The button should now have a tilt effect and you should have turnstile animations when navigating between the pages.

If you want to disable the tilt effect for a specific usercontrol you can add the SuppressTiltEffectBehavior on that control and the control will no longer have a tilt effect.

I’ve added a complete sample application showing all the transitions and tilt effect behaviors on the codeplex site of the Windows Phone Toolkit Behavior Extensions

If anything isn’t working contact me on twitter or post a comment

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Started a new Codeplex project: Windows Phone Silverlight Toolkit Behavior Extensions

Of all windows phone development that is done in the world I think almost everyone is using the Windows Phone Silverlight Toolkit you can get from Codeplex. This toolkit adds a lot of new controls and also other cool features as page transitions and a tilt effect on usercontrols so users will get more feedback when clicking in the UI.

This week I started working on a new project with a designer and he asked me how to insert the page transitions on a windows phone application page and I showed him that you’ll have to add a piece of XAML to your code and the page transitions will work. He asked me “Can’t I do this in the designer mode without touching any code?” I didn’t have any right answer for him so that’s why I’ve spend part of my weekend to build some behaviors that can be used to drag this functionality on pages in Expression Blend.

There are behaviors for every type of transition available in the silverlight toolkit. for each transitiontype there is an “in” and “out” behavior for entering and leaving the page. Besides the transition behaviors I’ve also created a behavior to turn the tilteffect on or off

  • EnableTiltEffectBehavior
  • SuppressTiltBehavior
  • TransitionRollInBehavior
  • TransitionRollOutBehavior
  • TransitionRotateInBehavior
  • TransitionRotateOutBehavior
  • TransitionSlideInBehavior
  • TransitionSlideOutBehavior
  • TransitionSwivelInBehavior
  • TransitionSwivelOutBehavior
  • TransitionTurnstileInBehavior
  • TransitionTurnstileOutBehavior

You can download the behaviors here: (important: you also need the silverlight toolkit for this to work)

http://phonetoolkitbehavior.codeplex.com/

On the codeplex site you’ll find a msi release containing the dll that you can include in your project to use these behaviors and I’ve also included a sample application. I’ll also upload the sample application to the marketplace so you can easily test out the performance etc without any trouble.

For a compete tutorial check this blogpost.

This is currently the first release so every feedback is welcome. please let me know by adding a comment here or contact me on twitter

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Microsoft Pubcenter not showing ads in your windows phone 7 app?

The free apps I had in the marketplace were running Google’s Admob as adprovider because when I wrote the apps Microsoft Pubcenter wasn’t available in the Netherlands yet. When I was upgrading my Apps to Mango I found out that version 4.0.4 that is currently the latest release of the Windows Phone Admob SDK is broken will always give you exceptions when you include this control. Seeing Google wasn’t to keen on fixing this since it was mentioned a lot in admob sdk Google groups I decided to switch to Microsoft Pubcenter because it came available for Dutch people.

Implementing the control is easy by just installing the SDK, create an account, adding the control to your page and filling in the applicationid and the adunitid. if you still need a guide this one explains all the details:

http://blogs.msdn.com/b/urmila/archive/2011/03/10/displaying-ads-on-windows-phone-7-apps-the-basics.aspx

So the control is added to the page and you’re ready to go. If you followed all the instructions the ads should show up fine. Not for you?

I had the same problem when I was testing my application. I did most of my testing in the emulator and the ads would show up fine right there. When I started testing on my phone I noticed that only the ad placeholder was shown for really short time and after that the ad was hidden. Trying to find out what the differences could be between my phone and the emulator my first thoughts were the Culture of the phone since my phone is running in Dutch Culture nl-NL and the emulator is running en-US by default. When I switched the culture on the emulator to being Dutch the ads also stop showing there.

So what is the problem and how did I fix it?

The Pubcenter Adcontrol has a nice event called “ErrorOccured” and you can subscribe to this event to see what is happening. (or just attach the debugger and set it to break on exceptions)

   1: public MainPage()

   2: {

   3:     InitializeComponent();

   4:     adcontrol.ErrorOccurred += new EventHandler<Microsoft.Advertising.AdErrorEventArgs>(adcontrol_ErrorOccurred);

   5: }

   6:  

   7: void adcontrol_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)

   8: {

   9: }

In the adcontrol_ErrorOccurred eventhandler you can log your error the adcontrol is throwing or handle it the way you want to. The error I kept getting when using the Dutch Culture was:

Microsoft.Advertising.Mobile.Shared.AdException – No ad available.

My guess was that this was happening because there aren’t any Dutch ads yet so I tried to change the settings of the adcontrol by changing the CountryOrRegion, Language and even the Latitude and Longitude attributes to somewhere in the United States but this doesn’t help. I made a ticket at the Pubcenter helpdesk and they told me a new algorithm just went live and it can be that there aren’t to many ads yet so it’s possible to get a disappearing ad control once in a while when you’re running less common cultures. Trying to change the country or culture DOES NOT WORK so you’ll just have to wait (It’s not like Admob is a better alternative since that one isn’t working at all)

I would encourage everyone to just leave the ad in and the requests to the Pubcenter servers will show that there is a lot of space for ads to be sold so advertisers will jump in and use this space.

Nokia seems the first to jump in because the last few days I seem to receive Nokia Lumia ads when using a Dutch culture :)

Oh btw this method also works when you’re having other issues with your ad control ofcourse. just check the exception to see what’s going on. The one thing I keep forgetting every time I add the AdControl are the capabilities in the WMAppManifest.xml. when you do this you’ll get another AdException:

Microsoft.Advertising.Mobile.Shared.AdException – Required capabilities are missing from manifest (WMAppManifest.xml): ID_CAP_NETWORKING, ID_CAP_PHONEDIALER, ID_CAP_IDENTITY_USER, ID_CAP_MEDIALIB, ID_CAP_WEBBROWSERCOMPONENT.

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

MIX 09 Keynote: Introducing Silverlight 3.0 (Beta available NOW!!!)

When I came home about an hour ago I turned on my mediacenter pc to listen to some mp3's when I thought.. Hey wasn't MIX 09 starting today? Maybe I can check out some video's already like I could with the pdc.

When I browsed to http://live.visitmix.com/ the Keynote was played LIVE in silverlight :) Scott Guthrie was already talking about StackOverflow.com and after that he started talking about Silverlight 3.0

Silverlight 3.0 is going to bring us some pretty cool stuff like Hardware 3d acceleration and multitouch support. These functions ofcourse are pretty cool but are they really usefull? one of the most important things Scott also announced was SEO optimization for Silverlight 3.0.

In Silverlight 3.0 you will be able to store points in your applications from where you can browse from and to by using your forward / back buttons but you're also able to create a bookmark and ofcourse the most important part is that it can be indexed by search websites so they can link to specific locations in the silverlight 3.0 app.

Another cool thing in Silverlight 3.0 is that if you build an application using some external libraries that the libraries can and will be downloaded only when they are used. and when you use the same library in a different silverlight app it will use your already downloaded version instead of pulling it from the server again saving bandwidth.

Sketchflow is a new feature build in Blend 3.0 which will enable you to create sketches of your design rapidly by dragging and dropping wiggely controls (pencil drawn looking controls) on a screen. You can also create a flow of the application fluently by creating several screens and connecting them together. After this you can add functionality to some navigation buttons (without writing code) to navigate from 1 screen to another. After this you can change your sketches to real working code and you’re done!

Multi Tier Data is another new feature which is working like a proxy representation of your data on the server inside your silverlight app. You can databind your controls to the proxy data and if you update the data it will automatically be synced with the server. It’s also possible for the server to push changes in the data to the client so you don’t have to poll the server anymore.

Scott rounded up his presentation telling that the current silverlight 3.0 package is smaller than the current silverlight 2.0 package and the beta 1 is released today! You can download it at:
http://silverlight.net/getstarted/silverlight3/default.aspx

Scott didn’t say anything about a final release date but he did mention later this year (so probably q4)

I really like the changes and can’t wait to start playing with SL 3.0

Geert van der Cruijsen

 

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Silverlight Design Pattern: the Model View ViewModel (MVVM)

Hi There,

The Customer where I'm currently working at asked me if i could build him a Silverlight 2 app. I've been playing around with Silverilght quite a bit but i haven't really used any design patterns so i came to the idea to search the web if there are any specific Silverlight design patterns.

The only really big pattern i found was the MVVM Model View Viewmodel pattern. This isn't a completly new design pattern (Martin fowler calls it the Presentation Model Pattern)

If you know the MVC pattern which you probably do know this is somewhat alike. The model is your layer which connects to the data and the view is ofcourse xaml based in silverlight. So what does the ViewModel do? The viemodel is used to build specific models for each view in your silverlight app so you can have full advantage of the strong databinding in Silverlight.

There are quite some resources about this pattern which i'll link down here:

I'll be using this pattern at my current assignment and afterwards i'll blog about the results :)

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Silverlight 2 and Flash 10 put to the test

Today a colleague of mine send me a link of a very cool site: http://www.shinedraw.com/

The guy who build the site is a webdeveloper with 6 years experience in building flash apps and 1 year of Silverlight experience. On his blog are a lot of apps build both in Flash and Silverlight. Some examples are: loading a big external image into the silverlight / flash app and a fps stress test.

http://www.shinedraw.com/data-handling/flash-vs-silverlight-loading-external-image/

http://www.shinedraw.com/mathematics/flash-vs-silverlight-fps-meter-stress-test/

It's very cool to see that the output of both platforms is almost equal, though in most test Silverlight is performing a bit better then Flash 10.

Also if you look at the code that is used in both examples you have to say that programming in Silverlight is a more pleasant experience.

Both platforms have strengths and weaknesses. Microsoft has visual studio which is far out the best IDE out there. Adobe on the other had has the best tools for designers.

The battle for best rich internet platform rages on!

 

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Silverlight 2 Control Toolkit ready for download

Yesterday Microsoft released the first version of the Silverlight Extended controls suite on Codeplex.

This control suite contains a number of special controls that are now available for the public to download and use in their own projects.

an example of what kind of controls are included in the toolkit:

  • TreeView
  • Charts
  • Expander
  • AutoComplete
  • NumericUpDown

On the codeplex site there are online demos of all controls which are included in the toolkit and the controls are also documented in the wiki on the page.

 Example of how the Treeview looks and how you use it:

 

Example of the AutoCompleteBox and how to use it in your xaml code: 

 

You can check out the online demos at codeplex: Controls demo and the Charting Demo

I really think Microsoft did a great job at offering these controls to the community and it will make developing in silverlight easier for everyone.

I liked the Charting part the most and i really look forward in using that in my projects in the future. Just look at how nice these controls look and how easy you can fit them into your project:

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Silverlight 2 Release Candidate Available

Last night Microsoft released the first release candidate for Silverlight 2.0.

 

There are a few new controls added in this release: the Combobox, passwordbox and the progressbar.

you can download the new silverlight release candidate at: http://silverlight.net/GetStarted/sl2rc0.aspx

on Scott Guthries weblog there is a nice explanation on how these new controls work.

New Silverlight controls

the new silverlight Controls (Combobox, passwordbox and the progressbar)

 

note that only the developer tools and runtime are released and not regular silverlight runtime. This is done so developers have time to upgrade their applications before silverlight 2.0 RC1 is actually released to the public.

Happy coding!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter