XAML Playground
about XAML and other Amenities

New e-book published

2014-02-10T12:31:42+01:00 by codeblock

Silverlightshow has published today another ebook creted wrapping up a number of articles I wrote in the previous months. The title may sounds ambitious:

Windows 8.1: The new less-known features that will improve your work

The ebook contains 12 chapters made of a collection of arguments that are not mainstream when thinking to Windows 8.1 features. It actually speaks about a number of featurs that has benne added to the most recent release of the platform but that are not really known. Here is the list of chapters:

  • Chapter 1: Behaviors SDK - Part #1
  • Chapter 2: Behaviors SDK - Part #2
  • Chapter 3: Exploring new controls (Hub, CommandBar, Flyouts and Pickers)
  • Chapter 4: Location-aware apps - Part #1: What's new in geolocation
  • Chapter 5: Animations and transitions
  • Chapter 6: Location-aware apps - Part #2: Working in background
  • Chapter 7: Play with Bluetooth Rfcomm
  • Chapter 8: Application Views improvements
  • Chapter 9: Improved device interactions
  • Chapter 10: Alarm and Lock screen call toasts
  • Chapter 11: Create a PDF Viewer with new PDF API
  • Chapter 12: The Windows Search API

The role of Behaviors and UserControls in the MVVM paradigm

2014-02-10T04:30:00+01:00 by codeblock

It is a well known fact that the Model-View-ViewModel pattern is a must when you develop with a XAML-related technology. By now, there are plenty of frameworks, toolkits and tools that imagesupports this programming model and also HTML/Javascript technologies are fast moving towards this architectural pattern using specific libraries like KnockoutJS and AngularJS. 

All in all, the aspects of MVVM programming have been consolidated and it is often clear what goes in the View and what goes in the ViewModel but, as usual, there are a number of degrees of gray between the white and the black and often you meet limits that need a workaround that violates the pureness of the pattern. So please notice that it is not a pretty formal matter, but the violation always takes inside of our architecture some dirty tricks that make it hard to understand, maintain and evolve in the future.

It's here that two actors enter the scene. They are named Behaviors and UserControls. Also if I've merged them into the same argument, they cover very different aspects. Behaviors are much more logic-related and are used to share a common "behavior" (that may have also a visual impact) to a number of different elements. UserControls instead are visual components and they are better to encapsulate visual elements thet should work in a coordinated way.

When do I need a Behavior or a UserControl?

When you work in a MVVM application, most of the time is spent moving data from a local or remote service to a couple of properties, connected to the user interface, and then collecting commands that indicates the actions accomplished by the user. Into the ViewModel you are completely abstracted by the user interface that consumes your properties. I usually pay attention to property names to avoid UI-related names. My view models never have properties called "Visible" or "Opened" because these imply a someway hard-coupling between the meaning of the name and what it happens in the user interface.

It may seem it suffices, but unfortunately, there are a number of cases that you have to switch on or off some special effect in the user interface and it is really hard to get it working only on the basis of a simple property that changes its value. It may be an animation, a fading effect, an item that appear or disapper, or also something that changes it shape suddenly. For all of these and other cases, you may need to write some UI-logic that does the dirty work, but the viewmodel is not the right place to put it.

Let do an example: UserControl

Let say you have to build a registration form. It is really simple to create a similar form and it is all about binding correctly properties together. But there is a subtle problem. the PasswordBox has a property that can't be subject to data binding. So, it is required to work around the problem. In this case, using a user control let you create a piece of code that receive the PasswordChanged event and updates a DependencyProperty.

   1: public partial class BindablePasswordBox : UserControl
   2: {
   3:     bool suspended = false;
   4:  
   5:     public static readonly DependencyProperty PasswordProperty =
   6:         DependencyProperty.Register(
   7:             "Password",
   8:             typeof(string),
   9:             typeof(BindablePasswordBox),
  10:             new PropertyMetadata(string.Empty, new PropertyChangedCallback((s, e) => ((BindablePasswordBox)s).OnPasswordChanged())));
  11:  
  12:     public BindablePasswordBox()
  13:     {
  14:         InitializeComponent();
  15:         this.thePasswordBox.PasswordChanged += thePasswordBox_PasswordChanged;
  16:     }
  17:  
  18:     private void thePasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
  19:     {
  20:         try
  21:         {
  22:             suspended = true;
  23:             this.Password = this.thePasswordBox.Password;
  24:         }
  25:         finally
  26:         {
  27:             suspended = false;
  28:         }
  29:     }
  30:  
  31:     private void OnPasswordChanged()
  32:     {
  33:         if (!suspended)
  34:         {
  35:             this.thePasswordBox.Password = this.Password;
  36:         }
  37:     }
  38:  
  39:     public string Password
  40:     {
  41:         get { return (string)GetValue(PasswordProperty); }
  42:         set { SetValue(PasswordProperty, value); }
  43:     }
  44: }

This control isolate the logic required to create the property and update it. The “suspended” field is used to avoid cyclic updates between the Password property of the PasswordBox and the same property of the user control. Once you have created the control, you can use it into the Views and use the databinding to connect the password to the viewmodel.

   1: <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
   2:     <local:BindablePasswordBox Password="{Binding Password, Mode=TwoWay}" />
   3:     <ProgressBar Minimum="0" Maximum="100" Value="{Binding Complexity}" HorizontalAlignment="Stretch" Height="5" />
   4: </StackPanel>

In this example I've imagined that the viewmodel cheks the password complexity avery time it changes and updates a percentage scale in the Complexity property. The progressbar gives a visual representation of this value but this is only matter of user interface.

Going with a Behavior

Behavior have been added to the XAML family after their inclusion in the Blend SDK 3.0. Immediately they become a first class tool to support development with MVVM, just because they are able to encapsulate a piece of code that can be easily reused. The probably most common usage of behaviors is the EventToCommand trigger that is used to map element events to viewmodel commands, but with a minimum of effort they can improve your MVVM programmi of a number of degrees.

imageLet say we have to build a IP configuration form. In this form we have a field where we can set the IP address if it is not acquired by a DHCP server. The field appear as the figure on the side

Once you select the dropdown list value ad "DHCP", the textbox on the side may behave in very different ways. We can hide it or also it can be disabled. The viewmodel should not be never aware of this fact. It only have a property the contains the IP Address and the IPMode (0 = DHCP, 1 = Manual).

To implement a reusable logic we can use a behavior here. Is should be the most generic so it wraps the FrameworkElement class:

   1: public class ShowHideBehavior : Behavior<FrameworkElement>
   2: {
   3:     public static readonly DependencyProperty ValueProperty =
   4:         DependencyProperty.Register(
   5:             "Value",
   6:             typeof(string), 
   7:             typeof(ShowHideBehavior), 
   8:             new PropertyMetadata(null, (s, e) => ((ShowHideBehavior)s).OnValueChanged()));
   9:  
  10:     public string Value
  11:     {
  12:         get { return (string)GetValue(ValueProperty); }
  13:         set { SetValue(ValueProperty, value); }
  14:     }
  15:  
  16:     public static readonly DependencyProperty ValidValueProperty =
  17:         DependencyProperty.Register(
  18:             "ValidValue",
  19:             typeof(string),
  20:             typeof(ShowHideBehavior),
  21:             new PropertyMetadata(null));
  22:  
  23:     public string ValidValue
  24:     {
  25:         get { return (string)GetValue(ValidValueProperty); }
  26:         set { SetValue(ValidValueProperty, value); }
  27:     }
  28:  
  29:     public bool HideWhenInvalid { get; set; }
  30:  
  31:     private void OnValueChanged()
  32:     {
  33:         if (AssociatedObject != null)
  34:         {
  35:             if (HideWhenInvalid)
  36:                 this.AssociatedObject.Visibility = object.Equals(this.Value, this.ValidValue) ? Visibility.Visible : Visibility.Collapsed;
  37:             else
  38:                 this.AssociatedObject.IsEnabled = object.Equals(this.Value, this.ValidValue);
  39:         }
  40:     }
  41: }

The behavior has a Value property that contains the value specified for the target combo box and a ValidValue that indicates the value for which the element is visible/enabled. Also there is a HideWhenInvalid property that let the developer choose if the control should be disabled or hidden. The followinf XAML uses the behavior:

   1: <StackPanel Orientation="Horizontal">
   2:     <ComboBox x:Name="cboMode" Width="100" SelectedIndex="{Binding IPMode}">
   3:         <ComboBoxItem>DHCP</ComboBoxItem>
   4:         <ComboBoxItem>Manual</ComboBoxItem>
   5:     </ComboBox>
   6:     <TextBox Width="200" Margin="8,0,0,0">
   7:         <i:Interaction.Behaviors>
   8:             <local:ShowHideBehavior HideWhenInvalid="true" Value="{Binding SelectedIndex, ElementName=cboMode}" ValidValue="1" />
   9:         </i:Interaction.Behaviors>
  10:     </TextBox>
  11: </StackPanel>

The logic, encapsulated in this way, is highly reusable and we can also implement a number of properties that allow the customization of behavior across different applications. Additionally, the ViewModel is completely separated from an aspect that is a question specific to the presentation and not to the business logic.

How to choose?

So the question now is: Should I use an UserControl or a Behavior? Unfortunately this question does not have a simple and unique answer. At the proof of facts, there are many cases where the solution are overlapped and you should choose on the basis of your personale feel, or better, on the basis of your project goals. My rules of thumb are the following:

First of all a behavior: It is really much more easy to implement a behavior than a user control if you need to do something more than extracing a chunk of XAML. Behavior are also much more reusable then UserControls and they can be parametrized easily.

Then try an UserControl: If a behavior does not match, as an example because it implies a too complex logic or needs to access properties that are not available, then the UserControl often is the right answer.

It involves generation of elements: In this case the UserControl is much more effective because you can use a base template in XAML and then add the required elements. In this case you can also evaluate a Custom Templated control if you think the code is widely reusable.

Another question is When? When should I understand I need something different than a ViewModel. This question has a much simple answer: When you need to go to your codebehind to implement such a feature, then probably you can write a behavior or an user control.

Conclusion

The examples I've shown in this post are really simple but I hope they give you the right feel about code encapsulation. The main purpose of creating components like user controls and behaviors should be the reuse of their logic, but there are a number of reasons why it is a good idea to use them also for non-reusabel features since they unplug your logic by the viewmodel.

WP8: New Emulators images released

2014-01-03T12:37:09+01:00 by codeblock

Some new emulator images are now available for the download. These new images - a total of 9 - covers the Windows Phone 8.0 Updates 2 (8.0.10322) and 3 (8.0.10492 or higher). They are freely downloadable from the Microsoft website from the links below:

Windows Phone SDK 8.0 Update for Windows Phone 8.0.10322
http://www.microsoft.com/en-us/download/details.aspx?id=39711

Windows Phone SDK 8.0 Update 3 Emulators
http://www.microsoft.com/en-us/download/details.aspx?id=41559

Both the updates requires at least Visual Studio 2014 Update 4 or Visual Studio 2013 RTM. They are targeted to the test of applications on the correspondent platform updates. Particularly the Update 3 enables the support for large screen devices (1080p). Here is the complet list of images:

Update 2
Windows Phone Emulator 8.0 (10322) WVGA
Windows Phone Emulator 8.0 (10322) WVGA 512 MB
Windows Phone Emulator 8.0 (10322) WXGA
Windows Phone Emulator 8.0 (10322) 720p

Update 3
Windows Phone Emulator 8.0 Update 3 WVGA
Windows Phone Emulator 8.0 Update 3 WVGA 512 MB
Windows Phone Emulator 8.0 Update 3 WXGA
Windows Phone Emulator 8.0 Update 3 720p
Windows Phone Emulator 8.0 Update 3 1080p

Take note that you must have the Windows Phone 8.0 already installed before to intalls the updates.

XPG Toolkit – Notification Library 1.0.5114.0 released

2014-01-02T21:28:29+01:00 by codeblock

During the writing of my last article for Silverlightshow where I’ve explained the new Alarm and Lock screen call Toast notifications, I found useful a small set of classes to generate the XML that I’ve created to build the notification. This short xml chunk must be created for Tile, toasts and badges and also if the framework has an method made to return the empty template is always something of boring.

Using some classes and an xmlSerializer I’ve finally arranged to make the creation of the xml simple as a breeze, and I’ve taken some time during my winter holidays to consolidate the toolset and complete it with tile and badge notifications. It definitely taken something more than a little time due to the fact that tile templates are really a lot of types…

So at the end the library has about 164 classes and is enforced by 136 unit tests made to ensure that the output template does not changes whit future developments. Together with the templates I’ve also created a couple of utility classes, supporting dependency injection, that enable the send of notifications with very few lines of code. Here is and example:

   1: INotificationManager manager = new NotificationManager();
   2:  
   3: manager.PublishToast(new Toast
   4:     {
   5:         Duration = "long", 
   6:         Launch = "12345",
   7:         Audio = new ToastAudio{
   8:             Loop = true,
   9:             Source = "ms-winsoundevent:Notification.Looping.Alarm2"
  10:         },
  11:         Visual = new ToastVisual
  12:         {
  13:             Binding = new ToastText01
  14:             {
  15:                 Text1 = "Alarm!"
  16:             }
  17:         },
  18:         Scenario = new AlarmScenario
  19:         {
  20:             CanDismiss = true,
  21:             CanSnooze = true
  22:         }
  23:     },
  24:     DateTimeOffset.Now.AddMinutes(1), 
  25:     TimeSpan.FromMinutes(1), 
  26:     5);

For a full explanation of the library please refer to this page that will be continuously updated with the new features I’ll add in the future. Feel free to contact me to suggest new features of to make me aware of bugs.

Here are the download links:

Package on nuget: https://www.nuget.org/packages/XPG.Toolkit.Notifications/1.0.5114

Download: http://www.xamlplayground.org/downloads/xpg-toolkit-notifications-1.0.5114.0-bin.zip (83kb)

Windows 8.1 available for the download

2013-10-17T05:40:00+01:00 by codeblock

Windows-8-1Today the new update to the Windows 8 operating system is available for the download. It adds a number of new features for the end user and for the developer. Together with the upgrade Microsoft released a number of upgrades for built-in apps that comes together with the operating system.

The update will be available directly from the Store app or as an ISO image. Some trouble may affect users that already installed the public preview using the ISO image. In this case it is required to return back toe the Windows 8 before installing the new 8.1. Differently, if you have installed the preview from the store, the upgrade should work effectively but all the apps must be reinstalled at the end.

There are important new features in user experience: the availability of new tile sizes that now have small, square, wide and large size, powering up the notifiations on this important surface. Now the operating system supports more than two apps on the screen at the same time, and the user is able to choose the size of each app. Skydrive become the official and integrated cloud media; the user can choose to automatically save contents to the cloud and see them sync between different devices.

For the developer the news are huge. Other to the toolset enhancements related to the previous news, it now has also a number of new features.

  • Many xaml improvements for developers
  • A Hub control that simplify the creation of hub-applications
  • A new set of tools for location and geofencing
  • News in share and search contracts
  • New types of toast notifications (alarm and lock screen)
  • Support for Appointments and Contacts
  • Enhanced bluetooth support that includes RfComm
  •  

Windows Phone 8 Overview (Slides)

2013-06-07T11:55:00+01:00 by codeblock

Here is the slide set from my last talk on Windows Phone 8.

Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Model View ViewModel with Windows Store Application

2013-03-08T21:20:28+01:00 by codeblock

I reference here the slides from this night talk about the Model View ViewModel in a Windows Store app. The talk and the slides are in Italian but I figure out you can use google translate to get the translation in you language.

Model-View-ViewModel con Windows Store Apps

Thanks to all the people that listened to my presentation and asked me a question about this topic. If you need my help please feel free to contact me via blog contact form.

The “evil” in using “async void”

2013-02-19T01:57:03+01:00 by codeblock

Following a non-NDA session at the MVP Global Summit 2013, the speaker pointed me to an interesting argument that is the usage of “async” with methods returning void. This practice is used many times, more than you expect, and is a potential source of interesting bad issues that can cause unexpected crashes in your apps.

The problem with “async void” versus the opposite “async Task” is that a method declared this way is something like a “fire and forget”, where the fired part is the body of the method and the forget part may be the problem. Let say you have a situation like this:

   1: public void Run()
   2: {
   3:     try
   4:     {
   5:         DoSomething();
   6:     }
   7:     catch(Exception ex)
   8:     {
   9:         DisplayError(ex);
  10:     }
  11: }
  12:  
  13: public async void DoSomething()
  14: {
  15:     throw new Exception("Something gone wrong...");
  16: }

The “DoSomething” method here throws and exception, probably due to an error in its flow. The problem is that, when this method is called, the developer cannot use the “await” because the method is declared as “void”. So, when the exception is thrown, the “Run” method has already exited. The direct result is that the Exception is pushed to the UI Thread and in a Windows Store app this means that the app crashes, without any advice.

This situation is much more common they you expect. consider the Dispatcher.RunAsync method:

   1: Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
   2:     async () =>
   3:     {
   4:         // do something here...
   5:     });

The declaration of the RunAsync method requires a delegate declared as “void”, so when you ask for an async lambda, this is called as in the previous example. An exception in the body of the lambda expression causes exactly and application crash. The soluton is to wrap the RunAsync method is a mathod that returns a Task, so it can be awaited. So please, always avoid using “async void” in your code and you will not drive crazy trying to understand what is going wrong in your app.

SilverlightPlayground is moving to XAMLPlayground

2012-07-01T16:00:00+01:00 by codeblock

In the day I got my MVP for the 6th time in a row (the fifth under the Silverlight expertise), I would like to make it official, a change that someone can have miss. If you watch at the page header of this site, the title is now "XAML Playground", just to be witness of a biggest change that has happened in the previous months.

Many of you are aware that, after the technology shift predicted by Bob Muglia during October 2010, lot of things have changed in the horizon of the technology from which this site has born. Silverlight today is not only Silverlight but a set of technologies now have their roots starting from its seed. We have Silverlight on the Windows Phone, we have Silverlight on the Embedded systems and, mostly important we have Silverlight on Windows 8 under the name of XAML.

And it is exactly reflecting the name change that happened in Windows 8, that I decided to slightly change the title from "Silverlight" to "XAML".

The reason of this change is probably clear. I strongly believe that the power of Silverlight is now part of something much more bigger and it has a bright future. All these technologies have a sole common denominator that is XAML.

So, as it happened since the start of this year, expect in the future, a number of posts on Silverlight in the various flavour, for the Web, for Windows Phone, for Metro UI and probably also for Windows (ops... WPF). 

From now please be aware you can use three domains to reach this site:

http://www.silverlightplayground.org

http://www.xamlplayground.org

http://www.metroplayground.org

So definitely, it is all about XAML

Categories:   General | News
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Metro: Incrementally load GridView and ListView with ISupportIncrementalLoading

2012-06-10T21:58:36+01:00 by codeblock

Developers that usually deal with web applications know that one of the pillar of this kind of applications is the use of paged result sets because moving a huge number of records form the server to the browser is not a good idea. Metro applications suffer the same problem. No matter that metro applications are not strictly web applications, the application architecture imply that the connection to a datasource have to be wrapped by web service call so the need of limiting the usage of the network is a strong requirements.

Metro introduces a new interesting method to mange pagine of data. Since the use of a common paging is deprecated by guidelines the requirement is to automatically load records when a user is about to the end of the items available on the user interface. This may be an hard task to do with components like GridView and ListView but thanks to the ISupportIncrementalLoading interface it may be easy like a game.

The ISupportIncrementalLoading interface has to be implemented by a collection. When a GridView detects this interface in the class provided in the ItemsSource property, it automatically change its behavior and works loading items only when they really need to fill empty space because the user reached the end. The definition of the interface is pretty simple:

   1: public interface ISupportIncrementalLoading
   2: {
   3:     bool HasMoreItems { get; }
   4:     IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count);
   5: }

The HasMoreItems property simply inform the consumer when there is more items to load. But the core of the interface is the LoadMoreItemsAsync method. As the name suggests this method works asynchronously and it have to load a number of items. The count parameter represents the number of items the consumer needs but the body of the method can load a different number, based on its paging size, and have to return the this number as a result into the LoadMoreItemsResult class.

You may expect that the loaded items have to be returned by this method but it is not true. Remembering that the interface have to be implemented by a collection, the method have simply to append the loaded items to the collection itself. So, this interface needs that the collection raises a CollectionChange event to update the user interface. An exaample is for sure much more clear:

   1: public class NaturalNumbers : ObservableCollection<int>, ISupportIncrementalLoading
   2: {
   3:     public bool HasMoreItems
   4:     {
   5:         get { return true; }
   6:     }
   7:  
   8:     public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
   9:     {
  10:         CoreDispatcher dispatcher = Window.Current.Dispatcher;
  11:  
  12:         return Task.Run<LoadMoreItemsResult>(
  13:             () =>
  14:             {
  15:                 int[] numbers = Enumerable.Range(this.LastOrDefault(), 100);
  16:                 
  17:                 dispatcher.RunAsync(
  18:                     CoreDispatcherPriority.Normal,
  19:                     () =>
  20:                     {
  21:                         foreach (int item in numbers)
  22:                             this.Add(item);
  23:                     });
  24:     
  25:                 return new LoadMoreItemsResult() { Count = 100 };
  26:     
  27:             }).AsAsyncOperation<LoadMoreItemsResult>();
  28:     } 
  29: }

If you attach an instance of this class to a GridView (or a ListView) it will show a series of natural numbers loading them incrementally when you scroll the control. Every time the GridView reach the edge of the screen it needs to load a number of items so, after having checked the HasMoreItems propertyit call the LoadMoreItemsAsync method and await for the end of the operation. Inside this method I start a new Task. This is required because I have to return something to wait to the caller and the AsAsyncOperation converts the Task to the requested async operation. Inside the thread I generate 100 numbers starting from last in the collection then I marshal this numbers to the ui thread and load them to the collection. Since the collection is Observable this updates the items in the user interface. Finally i return the number of items I generated.

As a more complex exercise I've prepared an example attached to the end of this post. This example use the incremental strategy to load images from Flickr search API. The application shown in the following screenshot implements the search contract. When a query is made it load a special collection and the items are loaded incrementally when the user scrolls the GridView.

screenshot_06102012_224133

For this purpose I've created a IncrementalSource class. This class implements the ISupportIncrementalLoading interface and is able to manage every data source that exposes a GetPage method. If you have this method already implemented in an application you can easily turn it to incremental loading in a breeze.

   1: public class IncrementalSource<T, K> : ObservableCollection<K>, ISupportIncrementalLoading
   2:     where T: IPagedSource<K>, new()
   3: {
   4:     private string Query { get; set; }
   5:     private int VirtualCount { get; set; }
   6:     private int CurrentPage { get; set; }
   7:     private IPagedSource<K> Source { get; set; }
   8:  
   9:     public IncrementalSource(string query)
  10:     {
  11:         this.Source = new T();
  12:         this.VirtualCount = int.MaxValue;
  13:         this.CurrentPage = 0;
  14:         this.Query = query;
  15:     }
  16:  
  17:     #region ISupportIncrementalLoading
  18:     
  19:     public bool HasMoreItems
  20:     {
  21:         get { return this.VirtualCount > this.CurrentPage * 25; }
  22:     }
  23:  
  24:     public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
  25:     {
  26:         CoreDispatcher dispatcher = Window.Current.Dispatcher;
  27:  
  28:         return Task.Run<LoadMoreItemsResult>(
  29:             async () =>
  30:             {
  31:                 IPagedResponse<K> result = await this.Source.GetPage(this.Query, ++this.CurrentPage, 25);
  32:                 
  33:                 this.VirtualCount = result.VirtualCount;
  34:  
  35:                 await dispatcher.RunAsync(
  36:                     CoreDispatcherPriority.Normal,
  37:                     () =>
  38:                     {
  39:                         foreach (K item in result.Items)
  40:                             this.Add(item);
  41:                     });
  42:  
  43:                 return new LoadMoreItemsResult() { Count = (uint)result.Items.Count() };
  44:  
  45:             }).AsAsyncOperation<LoadMoreItemsResult>();
  46:     } 
  47:  
  48:     #endregion
  49: }

In my example I've implemented a Flickr class that use the flickr.photos.search API. So when a search comes I create an instance of this collection in the ItemsSource property of the GridView.

this.gv.ItemsSource = new IncrementalSource<Flickr, FlickrPhoto>(search);

If you want to try this beautiful application please download the full code from the link below. Provide your own Flicks Api Key and run the example in Visual Studio 2012 RC.

Download: http://www.silverlightplayground.org/assets/sources/XPG.Examples.IncrementalLoading.zip

Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (11) | Comment RSSRSS comment feed

Review: Mastering LOB Development for Silverlight 5: A Case Study in Action

2012-06-05T23:13:46+01:00 by codeblock

image

Braulio Diez, a friend of mine I known during the TechED 2008 in Barcelona, together with other authors has recently written a book about Silverlight 5. The "Mastering LOB Development for Silverlight 5: A Case Study in Action", published by PackLib is an interesting book that is able to point the light on the Silverlight topic, mixing together a good scan about Silverlight 5.0 features and a number of "cases study" that focus the attention of the reader on the power of this, still unmatched and irreplaceable, piece of technology.

In a time that seems to be pointed to the most new evolutions, inside the new version of Windows, mostly directly derived from Silverlight, reading this book may be a useful exercise to understand what it can do and what someone can still do using XAML instead of HTML5.

My thanks to Braulio for the pleasant reading.

http://www.packtpub.com/mastering-lob-development-silverlight-5/book

Categories:   Review
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Metro: Implement a parallactic scrolling for your GridView

2012-05-19T00:56:36+01:00 by codeblock

A customer of mine asked me about how to create a "parallactic scrolling" for the background of a GridView. For people that do not know what it is, parallactic scrolling is when you have a background image scrolling slower than the foreground content. This tecnique is mostly used in games to give the impression of depth of field with the overlapping of a number of elements that moves slower when they apper to be far from the observer.

To have a good example of this beautiful effect you can try the music hub of your Windows Phone. The Panorama based scrolling, when coupled with a background image, automatically apply a parallactic effect when you move from a panel to the following.

Coming to Windows 8, there are some application installed by default that shows a similar effect. Weather and Finacial apps shows a partial parallactic effect when transitionig between the start screen and the right content. GridView, ScrollViewer and other controls does not automatically apply this effect (almost not in windows 8 CP), but a simple trick let you easily show the effect in your apps.

First of all you have to produce an element, that is greater than the viewport in the direction you desire your scrolling to work. In the application of my user group it is an image made of people an the total size is almost double of the medium size of a screen device. This image is aligned to left and goes out of the screen on the right. Here is the code:

   1: <Grid>
   2:     <Image x:Name="backImage" Margin="0,0,0,30" 
   3:             HorizontalAlignment="Left" VerticalAlignment="Bottom" 
   4:             Source="/Assets/parallax_people.png" Width="2250" Height="200" Opacity="0.5" />
   5:  
   6:     <ScrollViewer x:Name="hScroll" 
   7:                   Style="{StaticResource HorizontalScrollViewerStyle}" Margin="0">
   8:         <!-- insert your content here -->
   9:     </ScrollViewer>
  10: </Grid>

The trick I'm showing works only with ScrollViewer because it requires to handle the ViewChanged event, but you can for sure include a GridView into a ScrollViewer and have the effect enabled for the control. And obviously this also apply to ListView as well.

Now, going to codebehind is is required to subscribe the ViewChanged event. This event is raised every time the user scrolls the content. So I have to recalculate the offset of the background using the HorizontalOffset property and to map the value to the total width of the image. Here is the code:

   1: private void hScroll_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
   2: {
   3:     var delta = (this.hScroll.HorizontalOffset / this.hScroll.ScrollableWidth) * (backImage.ActualWidth - this.hScroll.ViewportWidth);
   4:     this.backImage.Margin = new Thickness(-delta, 0, 0, 30);
   5: }

Once you have connected the method to the View the trick is done. In this code I use the Margin property to move the image. At the first sight you would have used a TranslationTranform. Unfortunately the Render tranforms clips the image so I finally adopted the Margin property with a negative value.

In my example you can tune the speed of the content  varying the width of the background image, but nothing else is required.