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.

0 Comments

I wasn’t aware that the Async CTP worked with Windows Phone 7 until I read this good introduction by Kevin Ashley.It’s not just the await and async –keywords which got me excited, it’s the thought of using TPL with WP7.

Unfortunately getting the CTP 3 to install wasn’t an easy task. First time everything seemed to go alright, except I couldn’t find the samples or DLLs from anywhere. Turns out this is a common problem and it is caused by the Silverlight 5 and some Visual Studio Hotfixes. 

Here are the steps I had to take in order to get the Async CTP installed:

  1. Removed Silverlight 5 SDK through Programs and Features
  2. Removed the following updates through Programs and Features / Installed Updates:
    1. KB2615527
    2. KB2635973
    3. KB2549864

All of these can be reinstalled after Async CTP has been installed.

After going through the steps described above, Async with WP7 is a go:

        private async void ButtonClick(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine(await GetWebpage());
        }

        private async Task<string> GetWebpage()
        {
            return await new WebClient().DownloadStringTaskAsync(new Uri("http://www.bing.com"));
        }

Update: Thanks to lino to pointing out that also KB2645410 is known to cause issues.