Continuing our exploration of doing navigation in a WinRT XAML Metro-app, there’s one more crucial difference when the page navigation in WinRT is compared to the Windows Phone 7’s page navigation: The navigation cache. In the WP7 world, the page’s life time can be summarized with these three bullets (thanks to Peter Torr):

  • Forward navigation always creates a new instance
  • Pages that are removed from the back stack are released
  • Pages on the back stack are always cached

Contrast this with the WinRT-world where, by default, a new instance of a page is always created. This means that even when you’re navigating back, a new page instance is created.

Testing navigation cache

We can test the navigation cache by using the “Grid Application” template which comes with the Visual Studio 11. Let’s create a new app based on it. The app contains three pages:

  • ItemDetailsPage
  • GroupedItemsPage
  • GroupDetailsPage

Of which the GroupedItemsPage is the landing page of the app. Let’s modify that page’s constructor to write some debug info and then run the app. When navigating forward to GroupDetailsPage and then back, this is the output:

image

Two instances of the same page has been created: One when navigating forward to this page and one when we navigated back to the same page. This is a big difference when compared to the WP7-platform where navigating back always uses the same instance of a page.

Adjusting page cache: NavigationCacheMode

Fortunately we’re able to modify this functionality. Every page has a property called NavigationCacheMode which can be used to change how the navigation caching works on that particular page. The NavigationCacheMode has three possible values. From MSDN:

MemberValueDescription
Disabled0The page is never cached and a new instance of the page is created on each visit.
Required1The page is cached and the cached instance is reused for every visit regardless of the cache size for the frame.
Enabled2The page is cached, but the cached instance is discarded when the size of the cache for the frame is exceeded.

Also the Frame-object, which handles navigation for us, has a property called CacheSize which “Gets or sets the number of pages in the navigation history that can be cached for the frame.”

Testing navigation cache: NavigationCacheMode.Required

Let’s modify GroupedItemsPage so that we set it’s cache mode to “Required”:

<common:LayoutAwarePage
    x:Name="pageRoot"
    x:Class="Application8.GroupedItemsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Application8"
    xmlns:data="using:Application8.Data"
    xmlns:common="using:Application8.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    NavigationCacheMode="Required"
    mc:Ignorable="d">

And then let’s re-run our previous test. This time only one instance of the page is created:

image

But what happens if we modify the GroupDetailsPage’s (the page where we navigate to) cache mode to Required? After navigating two times forward to the page, we can see that only one instance was created:

image

This means that NavigationCacheMode affects both navigating backward and navigating forward.

How to mimic Windows Phone 7 navigation model

Is it possible to completely mimic the Windows Phone 7 navigation model? I’m not sure at this point. It could be possible if the platform had support for removing a page from it’s navigation history (similar to NavigationService.RemoveBackEntry). Maybe using this functionality in combination with the NavigationCacheMode-property could provide a similar navigation model.

The navigation cache is also an interesting aspect to think of when using the MVVM pattern. With WP7 platform we’ve used to think only about VM’s life time (singleton vs. per request) but with navigation cache we can also tweak the page’s life time. This may open up new opportunities.

0 Comments
  •   Posted in: 
  • UWP

Update 17.7.2012:

As Kyle Burns pointed out, these workaround are no longer necessary. "as of the Release Candidate because directly setting the Source property with a Uri works as expected."

Problem

In Windows Phone 7 it’s possible to bind Image-control’s Source-property to either to a string or to an Uri and they both work. In WinRT binding against an Uri doesn’t work.

Given the following XAML:

<ListBox x:Name="Items">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Width="500" Height="500" Source="{Binding Image}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

And the following view model:

public class ItemVM
    {
        public string Image { get; set; }
        public string Title { get; set; }
        public string Subtitle { get; set; }
    }

imageThe image is displayed correctly in WinRT. But if the view model contains an Uri instead of a string, the image isn’t displayed.

public class ItemVM
    {
        public Uri Image { get; set; }
        public string Title { get; set; }
        public string Subtitle { get; set; }
    }

This can be problematic if you want to share your VMs between different platforms.

One possible solution

If you need to get the binding against an Uri to work you can create the following value converter:

public class ImageUriValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var uri = value as Uri;
            if (uri == null)
                return null;

            var result = uri.ToString();
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }

And use that in your binding:

<Page.Resources>
        <local:ImageUriValueConverter x:Name="Converter"/>
    </Page.Resources>
    
    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <ListBox x:Name="Items">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Width="500" Height="500" Source="{Binding Image, Converter={StaticResource Converter}}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

Another possible solution

This sounds like an beta-issue which could be very well fixed in the final release.

Update 5.2.2012

Morten posted a great tip in the comments. For some reason the blog doesn't allow me to approve it, so here's his whole comment:

Try this instead: 
<Image> 
    <Image.Source> 
         <BitmapImage UriSource="{Binding ImageUri}" /> 
   </Image.Source> 
</Image> 
   
This avoids all the converter code, and also allows you to be more specific on your BitmapImage wrt CreationOptions, DecodePixelSize etc. (however with a converter let me suggest you convert to a BitmapImage instead of string, or you'll just hit more converters when processing the binding)

9 Comments
  •   Posted in: 
  • UWP

Until we get the great frameworks like Caliburn.Micro up-to-date with WinRT, one possible solution for doing navigation when using MVVM pattern is to wrap the Frame-object. Here’s a simple implementation (which could be further enhanced by extracting an interface from it): 

public class NavigationService
    {
        readonly Frame frame;

        public NavigationService(Frame frame)
        {
            this.frame = frame;
        }

        public void GoBack()
        {
            frame.GoBack();
        }

        public void GoForward()
        {
            frame.GoForward();
        }

        public bool Navigate<T>(object parameter = null)
        {
            var type = typeof(T);

            return Navigate(type, parameter);
        }

        public bool Navigate(Type source, object parameter = null)
        {
            return frame.Navigate(source, parameter);
        }
    }

The NavigationService can be initialized by passing in the root frame, for example in the App.xaml.cs where the root frame is created: 

// Create a Frame to act navigation context and navigate to the first page
            var rootFrame = new Frame();
            App.NavigationService = new NavigationService(rootFrame);

            rootFrame.Navigate(typeof(BlankPage));

If you’re using some container to create your view models, the NavigationService-instance can be registered into it as a singleton. If you’re using a simple ViewModelLocator without a container, the NavigationService can be added as a property to the App-class and it can be accessed when creating the view models. In either case, the NavigationService should be passed to the VM through the constructor, after which navigation from a view model is a straightforward task.

Here’s an example of a view model which uses the NavigationService to navigate forward to a new page:

public class BlankPageViewModel
    {
        private readonly NavigationService navigation;

        public BlankPageViewModel(NavigationService navigation)
        {
            this.navigation = navigation;
        }

        public DelegateCommand GoToNextPage
        {
            get
            {
                return new DelegateCommand(x => navigation.Navigate<SecondPage>(), x => true);
            }
        }
    }

The BlankPageViewModel is constructed inside the ViewModelLocator-class: 

public BlankPageViewModel BlankPageViewModel
        {
            get
            {
                return new BlankPageViewModel(App.NavigationService);
            }
        }

A sample app containing two pages and the NavigationService-wrapper can be found from GitHub. The sample app also shows a basic implementation of the view model locator.

107 Comments
  •   Posted in: 
  • UWP

Color me surprised when I noticed that WinRT is missing the Thread.Sleep-function. Fortunately MSDN forums provided the following code snippet which quite nicely provides the same functionality:

static void Sleep(int ms)
{
   new System.Threading.ManualResetEvent(false).WaitOne(ms);
}

 

Source

8 Comments
  •   Posted in: 
  • UWP

After getting the Visual Studio 2011 to work with Windows 8 Consumer Preview, I've been trying to get my head around the WinRT / Metro-details. For now, I’ve decided to stay with the XAML-side of things, because that’s the most familiar to me. It’s been interesting to learn how everyday tasks are handled with WinRT when compared to a platform like WP7.

On a side-note: I’m not sure if I should be talking about writing “Metro-style apps” instead of “WinRT-apps”. I suppose time will tell which will become the de facto but personally I like the WinRT more.

Page navigation

Compared to the Windows Phone 7 –platform, navigating between different parts of the application is very similar in WinRT. The WinRT-app can contain multiple pagesand navigating between them requires just a call to a Navigate-method. What’s good is that you don’t have to navigate using the URIs like in WP7 and instead you can just pass in the type of the next page.

this.Frame.Navigate(typeof(BlankPage));

imageGiven that we have created a Blank Application project and added an another BlankPage to it, we can easily navigate from the first page to the next page:

<Grid>
     <Button Content="Navigation" Click="GoForward"/> 
</Grid>
private void GoForward(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(AnotherPage));
}

If we run the app, we can see that navigation works. But there’s no way for the user to navigate back.

Navigating back

Navigating back to the previous page is even easier than navigating forward. From the second page we just need to call the GoBack-method:

this.Frame.GoBack();

Passing parameters

In Windows Phone 7, passing parameters between the pages requires that the parameters are added to the query string of the navigated page. In WinRT we can pass objects.The object is passed using the second parameter of the Navigate-method:

this.Frame.Navigate(typeof(AnotherPage), customer);

In the page where we are navigated to we can access the object using NavigationEventArgs.Parameter:

protected override void OnNavigatedTo(NavigationEventArgs e) 
{ 
    var cust = e.Parameter as Customer; 
}

Navigating back multiple pages

Navigating back multiple pages in WinRT is easier than in WP7. We can call the GoBack-method multiple times in a loop. In WP7 this would cause an exception. Given a situation where we add a third page to the app and want it to have “Go Home” –button, we can call the following code which will navigate the user back to the first page:

while (this.Frame.CanGoBack) 
{ 
    this.Frame.GoBack(); 
}

Defining the first page

In WinRT, the application’s start page can be configured through the App.xaml.cs. Replacing the BlankPage with AnotherPage makes our app to start from the second page:

protected override void OnLaunched(LaunchActivatedEventArgs args) 
{ 
    if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) 
    { 
        //TODO: Load state from previously suspended application 
    }

    // Create a Frame to act navigation context and navigate to the first page 
    var rootFrame = new Frame(); 
    rootFrame.Navigate(typeof(AnotherPage));

    // Place the frame in the current Window and ensure that it is active 
    Window.Current.Content = rootFrame; 
    Window.Current.Activate(); 
}

Navigation in MVVM

Here's a separate post which shows one way to do navigation when using MVVM pattern.