WP8 Emulator Weirdness

I bumped into an issue that IMHO shouldn’t be an issue today. Not quite sure if it is related to portable HttpClient library that I am using, but I am going to put it out there is someone else bumps into the same issue.

I am writing a simple NewsBlur client for Windows Phone 8 and my app works well on my device now so I wanted to see how it looks in other resolutions supported by WP8. And to my surprise every request I made through HttpClient library returned status 404. Huh?

Turns out that IE on the emulator isn’t configured when you run the emulator. So when I tapped on IE I was presented with this:


Once I had that out of my way and I tried to run my app again it worked. Huzzah!


The above no longer works. I seem to have bigger issues with the emulator. Sigh… I’ll try¬†re-installing.

Playing with Kinect

Kiandra IT recently organised a hackaton titled Touch and Gestures. As you might guess it ended up being mostly about gesture enabling different things. Touch has been around for so long that most of us perceive it as something normal. While gestures are not new either there are some new exciting developments in that area going on, I am talking about https://www.leapmotion.com/. There is a lot of potential there. And of course there is the well known Microsoft Kinect.

There were four teams and the guys worked on a windows management system using Leap Motion, Kinect enabled story wall, a Leap Motion enabled web dashboard and of course the thing I am going to write about here :)

I teamed up with a colleague to Kinect enable my 3D Snooker game.  Here is a quick video of what we came up with (this is a slightly tweaked version, but the core remains the same).

So how does one go about using Kinect in a MonoGame?

Initializing Kinect is easy:

            KinectSensor _sensor = KinectSensor.KinectSensors.First();
            _sensor.SkeletonStream.Enable(); // Enable skeletal tracking

First we get a reference to Kinect sensor, then enable tracking of data we are interested in and start the whole thing. In our case we opted to enable SkeletonStream as we wanted to track position of our hands.

Next we need to handle Kinect events. We opted to use RX extensions and observe the event stream that way. At this point my colleague took over as he is a bit of a gun when it comes to using RX extensions. Here is the code:

            var skeletonData = new Skeleton[_sensor.SkeletonStream.FrameSkeletonArrayLength];
            var events = Observable.FromEventPattern<SkeletonFrameReadyEventArgs>(_sensor, "SkeletonFrameReady").Publish();
            var skeletons = events
                .Select(e =>
                        using (var skeletonFrame = e.EventArgs.OpenSkeletonFrame())
                        // Open the Skeleton frame
                            if (skeletonFrame != null)
                            // check that a frame is available
                                return skeletonData.LastOrDefault(x => x.TrackingState == SkeletonTrackingState.Tracked);
                            return null;
                .Where(x => x != null);

            var handVectors = skeletons.Select(GetHandsVector);

            // calculate angles and speed


In a nutshell, we subscribed to SkeletonFrameReady event and whenever we had a skeleton frame in Tracked status used that data to calculate the vector between left and right hand.
The vector was calculates simply by substracting right hand’s position from left hand’s position, like so:

        private static Vector3 GetHandsVector(Skeleton sk)
            var rightPosition = sk.Joints.First(x => x.JointType == JointType.HandRight).Position;
            var leftPosition = sk.Joints.First(x => x.JointType == JointType.HandLeft).Position;
            return ToVector3(leftPosition) - ToVector3(rightPosition);

        private static Vector3 ToVector3(SkeletonPoint leftPosition)
            return new Vector3(leftPosition.X, leftPosition.Y, leftPosition.Z);

As you move your hands the vector changes and we used it’s angle relative to X and Y axis to rotate the cue. Simple! :)

We also wanted to use gesture to trigger a shot and the idea was to track the speed as you move hands together, then, when hands are close enough to each other we would take that speed and trigger the shot. This is something that still doesn’t work quite well. We were dealing with two problems here:

  • How to stop the cue from rotating when you want to make a shot and
  • Getting an accurate speed reading.

After the hackaton (actually today) I solved the first problem by cheating a little bit. If you looked at the video above you probably noticed that I was holding a wireless mouse. I decided to use left mouse click to lock rotation in. Right mouse button click is used to switch between moving the cue ball (when allowed) and rotating the cue. I’ve been told that Kinect for Windows allows you to track palm movements, so when you make a fist that is treated like a click. I am using Kinect for XBox 360 here and this one does not support such funky things. So the trick with a wireless mouse is here to stay until I get my hands on Kinect for Windows.

The problem with speed remains though. So how do we calculate the speed?

            // calculate distance between hands
            Distances = handVectors.Select(x => x.Length());

            // determine if there was a shot played
            const float NEAR_ZERO = 0.3f;
            var distanceTime = Distances.TimeInterval();
            var speeds = distanceTime.Zip(distanceTime.Skip(1), (a, b) => Math.Abs((a.Value - b.Value) / (a.Interval.TotalMilliseconds - b.Interval.TotalMilliseconds)));
            Shoots = speeds.WhereOther(Distances, x => Math.Abs(x) < NEAR_ZERO);

First we track the distance between hands and the time intervals at which frames are coming in. The speed is the distance traveled divided by the time it took to travel this far. Just as your physics teacher told you ūüėČ

We only report speeds to the game engine once hands are close enough to each other. Like I said, there are still some issues and this method is somewhat unreliable. But I am yet to have any new ideas.

This is it. Hope you found it interesting :)

The Actor Framework for Windows Azure

I listened to Erik Meijer’s keynote at a developer conference I attended a while ago and on his way to convince us that SQL is bad he mentioned ActorFX framework.

I find the concept of an actor in the cloud to which you can push function delegates on the fly really interesting. The framework is still in early alpha stages and that is to a certain extent true for documentation too :) The code snippets are a bit inconsistent, but the accompanying text explains the concept very clearly.

So what are these actors in the cloud? Here is how I understand the thing:

  • The actor can keep anything as its state and that includes function delegates or actor methods from uploaded assemblies. As far as an actor is concerned function delegates are part of its state, behaviour is state.
  • Actors can run in a cluster, with state being replicated amongst them
  • Clients can change actor state or add new things to state (which includes assemblies with actor methods)
  • There is no need to recycle actor when uploading new versions of actor methods, the behaviour of the actor changes immediately
  • Clients can subscribe to updates made by other clients
  • Actors support transactions and idempotence¬†

The example Erik showed during his keynote was an observable list that lived in the cloud, but given how flexible actors are you could implement actors that are able to do many different things.

More details about ActorFX can be found here.

Microsoft Surface

At work we have a few Microsoft Surface devices that anyone can borrow and it was my turn to play with it over the last 4 days :)

I never owned a tablet and if you are wondering if I am itching to buy one now then read on ūüėČ

The truth is that I mainly write apps for Windows ecosystem, mainly because I am good at C#, having said that I could be using C# to write apps for iOS and Android as well, but I find the license costs for MonoTouch and Mono for Android a bit prohibitive. Anyway, this is why I am more inclined to buy a Windows 8 tablet. Not because I would think that iPad or Android tablets are crap, purely being pragmatic here.

So I had Microsoft Surface at my disposal for the last few days and I realized I don’t really need a tablet. Whether I want one is¬†a different question though ūüėČ

I still found myself using my laptop more than the tablet. I suppose I am more of a creator than consumer and for someone who creates content the tablet world is still lacking. And TouchCover cannot replace a good keyboard and a great touchpad or a mouse.

I am in fact, writing this blog post on the TouchCover keyboard. I do think what Microsoft has done with it is ingenious, but still a compromise. Good for quickly typing away some notes, but a bit frustrating when writing longer texts. Still I think they have done a great job, good to see innovation like this coming from Microsoft, they have been horrendous at marketing their innovations in the past. And if you follow them a bit more closely there is lots of interesting things Microsoft Research is working on.

I think it would be nice if Surface had 3G or 4G connectivity as well and personally I see more value in a tablet running on Intel Atom Clover Trail platform.

No major complaints about the rest of the tablet. Windows 8 is a smooth OS, the build quality is awesome and the Windows store is growing fast in size too. Even though I never really understood the bragging about app numbers from all players in the market. I mean, how many of those apps are actually any good? Writing a good app is actually not that easy. It is not just about being a good developer, you have to know a thing or two about UX and marketing too.

My major complain is actually about the price of this thing and the price of tablets in general. I just don’t think a 32GB 10′ tablet should be priced above $400. And that extends to Apple products as well, while Android does have some products in this price range.

And I am unhappy about the unavailability of Windows 8 tablets in stores. I’ve read that Microsoft is unhappy with sales, but then again, even if you want a tablet (talking about tablets other than Surface here) they are incredibly hard to find. Some say this could be down to some issues Intel is having with their new Clover Trail SOC, OEMs say that the demand is low, others say that retailers just want to clear old Windows 7 stock first. Personally I think it is just a load of bullshit and Microsoft and OEMs need to get their act together.

So yeah, I won’t be buying a Surface. But I do want a tablet so I can test my creations. But I’ll resort to eBay in search of a bargain or just wait until there are some cheaper options on the market. I do hope someone comes up with a 7′ tablet in the near future. If it is priced between $300 – $400 I would buy one, that would be an ok price even though it would not see a lot of use apart from app testing and a little bit of browsing and video watching when I don’t have my laptop near me.

How to figure out if a point is within triangle

While playing around with XNA and my simple Snooker game I bumped into a geometrical problem, basically I wanted to know if the ball coordinate is in the corner of the table, which in my simple game equates to determining if a coordinate is inside a triangle near table corner.

I was looking at the algorithm I wrote in the original DirectX version of this game and quite frankly I had no idea what I was doing there. Speaking of which, my code from 10 years ago is quite shocking, I came a long way since :)

Anyway, after scratching my bald head for a while I came up with this.

I am dealing with a triangle that has two sides of the same length, mathematicians would call it an Isosceles triangle. What I did first was calculate how much into the pocket the ball was along X and Y axises and if the sum of these two is bigger than the size of the triangle then I assume the coordinate is inside triangle.

In the image below Px + Py is greater than Sx (which is the same as Sy since the sides are of equal length) and P is inside triangle.


Now consider the image below, here the sum of Px and Py is less than Sx (Sy) and my coordinate is outside of the triangle.


Using gestures in MonoGame (and XNA)

I was trying to use this bit of code yesterday, but it didn’t work:

        protected override void Update(GameTime gameTime)
            while (TouchPanel.IsGestureAvailable)
                var gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.FreeDrag)
                    _cue.Rotate(gesture.Delta, GraphicsDevice.Viewport.Bounds);


Why? Because I forgot to enable gestures! This line was all that was missing:

            TouchPanel.EnabledGestures = GestureType.FreeDrag;

EnabledGestures is a flag property so you can enable multiple types of gestures by using bitwise or, like, for example:

 TouchPanel.EnabledGestures = GestureType.FreeDrag | GestureType.Tap;

In my rotate method I simply translate the delta into something more useful, which in my cases are degrees:

        public void Rotate(Vector2 delta, Rectangle viewPortBounds)
            var degreesAroundYAxis = (delta.X / viewPortBounds.Width) * 360;
            var degreesAroundXAxis = (delta.Y / viewPortBounds.Height) * 90;
            Rotation += new Vector3(MathHelper.ToRadians(degreesAroundXAxis), MathHelper.ToRadians(degreesAroundYAxis), 0.0f);

            if (MathHelper.ToDegrees(Rotation.X) < 5.0f)
                Rotation = new Vector3(MathHelper.ToRadians(5.0f), Rotation.Y, Rotation.Z);

Starting with MonoGame

I love coding little apps for my phone and (hopefully soon) tablet. The project I am working on now is porting a simple Snooker game I wrote using DirectX and C++ nearly a decade ago over to Windows 8 and Windows Phone devices.

My initial plan was to just copy my C++ code to a Direct3D project, tweak a few things and see it run. An overly optimistic goal, given my rusty C++ skills and the fact that DirectX API has evolved a lot since DirectX 8. So I started looking for alternatives that would get me to my goal quicker (I like to keep my hobby project short). If XNA had support on Windows 8 and Windows Phone 8 devices I would go with that one, but since they are not I started looking at MonoGame which is an open source implementation of XNA API. And it is awesome.

To get started you need to get MonoGame source code from GitHub by cloning the repository. The source contains VS2012 templates, copy these over to your templates folder and you are ready to start coding with MonoGame. For more details on how to do this follow instructions at bob’s blog. But you will need to (or can) do certain things differently!

First, MonoGame project has evolved a bit since and now you will have three VS2012 templates in there:

  • Game is the one you want to use if you are writing a game using MonoGame only,
  • XamlGame is a combination of MonoGame and XAML and
  • WindowsPhone is obvious

Secondly, before you can load your mesh models into your game you need to convert them into XNB file format, but at the moment there are no Content Importers in XNA. So you will need to use project templates that come with XNA Game Studio in order to convert the models to XNB format. There were some issues with installing XNA on Windows 8 in the past (see Aaron Stebner’s WebLog) but if you install Windows Phone 8 SDK it installs without a problem and you can use XNA Content project from VS2012. Then create a “Content” folder within your MonoGame project and copy XNB files in there (mark them as Content in properties and make sure they are always copied to output directory). I believe you could tweak the location by changing the line below in your Game class:

Content.RootDirectory = "Content";

This should have you ready and going. As for myself, I have this after one day:


An overdue first post

This should have been the first blog post here, but nevertheless.

Up until now I have been too lazy to start a blog, most projects I start at home eventually fizzle out and I never end up finishing them or they just aren’t polished enough, but after reading Scott Hanselman’s blog a while ago where he encouraged everyone to start blogging I decided to give it a shot and start blogging about things I mess around with at home. If you find the content here helpful then great, if not then let me know how I can improve (and by that I mean in a nice civilised manner, trollish comments will be deleted).

Some of the things are going to feel a bit outdated (like the WCF Dynamic Proxy post today), but I still see those things as relevant or else I wouldn’t be putting a post up about them. WCF might not be hip but it still is a technology that is used a lot in the enterprise.

I consider myself to be a jack of all trades, can do most things but I am not necessarily very good at everything and this blog is going to be a mix of everything.

Now let’s get it going!

Dynamic WCF Proxy

I find it hugely annoying to refresh Service References after every change to service contract. Having said that, if your services are public and you have external consumers for your services you don’t really want to make big breaking changes to your service contract anyway.

But when services are limited to your project or organisation/client you are more likely to change things and maintenance of service references can become a bit tedious then, especially when you have dozens of service references.

But there is an easier way! You can programatically create your service proxies, which, of course, is not without drawbacks as creating a WCF proxy on the fly is quite an expensive operation. The drawbacks can be countered by trying to cache and reuse proxies whenever possible.

And this is what I have done in DynamicWCFProxy library. You can download it from GitHub.

Using it is as easy as this:

            using (var client = new ProxyBase<IMyService>())
                Console.WriteLine(client.ExecuteProxyFunction(() => client.Proxy.GetData("Dude", 34)));

Where IMyService is your WCF service contract and GetData is one of it’s methods. As you can see ProxyBase is the magical thing that manages the lifecycle of the proxy. Proxies are pooled (the maximum number of proxies in pool being limited by the configured number of connections per endpoint) and as soon as we are out of the using block the proxy will be returned to the pool, ready to be used by some other thread. Every proxy has a connection life cycle strategy, which defaults to keep the connection open for a while to avoid reopening it if we do multiple requests to the same service in a sequence.

Now the life cycle strategy might work or not work in your scenario. With WCF you always want to do some performance testing around your app. And it could be that the default life cycle strategy is not your cup of tea, but you can always create your own and then write your code like this instead:

            using (var client = new ProxyBase<IMyService>(new MyConnectionLifeCycleStrategy<IMyService>()))
                Console.WriteLine(client.ExecuteProxyFunction(() => client.Proxy.GetData("Dude", 34)));

MyConnectionLifeCycleStrategy must inherit from ConnectionLifeCycleStrategyBase and the rest is up to you. Let’s have a look at default implementation in the library:

    public class DefaultConnectionLifeCycleStrategy<T> : ConnectionLifeCycleStrategyBase<T>
        where T : class 
        private readonly object _connectionLock = new object();
        private DateTime _lastUsed;
        private Timer _timer;
        private int? _maxConnectionIdleTime;
        private int MaxConnectionIdleTime
                if (_maxConnectionIdleTime == null)
                    // take send timeout (operation timeout) and add 5 seconds on top of it to get the idle time after which connection should be closed
                    // this is to avoid closing the connection before it timeouts which could lead to confusing error messages
                    _maxConnectionIdleTime = Convert.ToInt32(EndpointContext.ServiceFactory.Endpoint.Binding.SendTimeout.TotalMilliseconds) + 5000;

                return _maxConnectionIdleTime.Value;

        public override T Open()
            lock (_connectionLock)
                var proxyOut = base.Open();

                _lastUsed = DateTime.Now;

                return proxyOut;

        public override void Close()
            lock (_connectionLock)

        private void StartConnectionCheck()
            if (_timer == null)
                _timer = new Timer(ConnectionCheck, null, MaxConnectionIdleTime, MaxConnectionIdleTime);
                _timer.Change(MaxConnectionIdleTime, MaxConnectionIdleTime);

        private void ConnectionCheck(object state)
            lock (_connectionLock)
                DateTime checkAt = DateTime.Now;
                if ((checkAt - _lastUsed).TotalMilliseconds >= MaxConnectionIdleTime)

        private void StopConnectionCheck()
            _timer.Change(Timeout.Infinite, Timeout.Infinite);

As mentioned, the default strategy is to keep the connection open for as long as possible to avoid having to reopen the connection. This is why in the constructor we read endpoint idle timeout configuration and calculate the max open time based on this. Note that if we have an operation running which is going to timeout we still want to see a timeout exception, hence why max connection open time is 5 seconds longer than configured endpoint idle timeout. Next notice that this strategy keeps track of when the connection was last used which means the connection will remain open for MaxConnectionIdleTime after last call was made, and if a new call is made that gets extended again. A background timer will close the connection if we reach MaxConnectionIdleTime timeout.

Well this is it. I hope you find this useful!

Creating your own photo viewer app for Windows 8


In Windows 8 you can use the Photo app to view pictures in My Pictures folder. While the Photo app has lots of features and is updated with new ones quite often there is one feature I miss Рthe ability to navigate between pictures in the same folder as the picture I just clicked on.


Writing a Windows Store app that solves the problem is very easy and here is how we do it.

If you are running Visual Studio on Windows 8 it comes preinstalled with templates to build Windows Store apps. For the purposes of this tutorial we are going to use the Blank App XAML template. I am going to name my app PhotoViewer.


Next we need to declare what the app needs to do it’s work and what it can do. Double-click Package.appxmanifest file in Solution Explorer, click on¬†Capabilities¬†tab and tick¬†Pictures Library,¬†this will give us access to user’s Pictures library, which is also a limitation of our app – we can only use it to view pictures that are stored in Pictures library.

We don’t need¬†to connect to internet so you can¬†untick¬†Internet (client)¬†capability.


Next we are going to declare that our app can handle certain types of files. Navigate to Declarations tabs and add File Type Associations from Available Declarations dropdown. In the left pane type in Display Name and Name. Display Name is going to be used to describe the files this app can open, Windows Explorer will use this value to describe the files if you make PhotoViewer the default app to open files it supports. Next, tick Open is safe checkbox, if you wish you can tick Always unsafe if you want the user to confirm before file is opened. And lastly, add Supported file types. For the purposes of this example we are going to support jpg files, but you can add as many as you wish. Anyway, to add jpg type in image/jpeg in Content type and .jpg in File type text box, just like on the screenshot below.


With configuration done we can do some coding.

Open App.xaml.cs and override OnFileActivated method. The code we are going to put in OnFileActivated looks like this:

        protected override void OnFileActivated(FileActivatedEventArgs args)
            var rootFrame = Window.Current.Content as Frame;

            if (rootFrame == null)
                rootFrame = new Frame();

            if (args.Files != null && args.Files.Any())
                rootFrame.Navigate(typeof(MainPage), args);
                Window.Current.Content = rootFrame;
                var p = rootFrame.Content as MainPage;


In here we are setting up the contents of the app by creating a new Frame object which acts as a container for our pages. Our app’s starting page is¬†MainPage¬†so¬†we¬†navigate to¬†it and passing file activation arguments to it.¬†When MainPage is navigated to we need to set our data source. In order to do so we will tweak MainPage.cs like so:

    public sealed partial class MainPage : LayoutAwarePage
        private FolderViewModel _viewModel;

        public MainPage()
            _viewModel = new FolderViewModel();
            DataContext = _viewModel;

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("DataContext"))
                _viewModel = (FolderViewModel)pageState["DataContext"];
            else if (navigationParameter is FileActivatedEventArgs)
                await _viewModel.Initialize((FileActivatedEventArgs)navigationParameter);

            // To make debugging easier this code is only included in release mode
            if (!_viewModel.ContainsPictures)
                await ShowWarningAndClose();

        private async Task ShowWarningAndClose()
            var messageDialog = new MessageDialog("To use PhotoViewer select a picture in Pictures Library first.", "No Picture Selected");

            messageDialog.Commands.Add(new UICommand(
                new UICommandInvokedHandler(this.CommandInvokedHandler)));

            await messageDialog.ShowAsync();

        private void CommandInvokedHandler(IUICommand command)

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
            pageState["DataContext"] = _viewModel;

First, note that I have changed MainPage class to inherit from LayoutAwarePage. LayoutAwarePage is a class that is included in other Windows Store app templates, such as Grid App XAML template. It handles a number of page navigation aspects hence I copied it over to my PhotoViewer app. When you copy this class over also copy BindableBase and SuspensionManager classes, we will need them. Next notice that I am setting DataContext to our view model in MainPage constructor, but this is not where the view model is initialized.

View model initialization occurs in LoadState method. There are two ways of initializing the view model; we could be coming back to MainPage in which case the view model is initialized from page state (which gets saved in SaveState method) or we could be navigating to the page for the first time in which case we initialize view model based on the arguments that were passed in.

This class also contains some code to notify the user when there is nothing to display but that is fairly straight forward. Let’s have a look at the FolderViewModel class instead:

    internal class FolderViewModel : BindableBase
        private ObservableCollection<PictureModel> _pictures = new ObservableCollection<PictureModel>();
        public ObservableCollection<PictureModel> Pictures 
            get { return _pictures; }

        private async Task SetPictures(IEnumerable<StorageFile> pictures)
            foreach (var picture in pictures.Select(f => new PictureModel(f)))
                await picture.Initialize();

        public bool ContainsPictures { 
            get { return Pictures != null && Pictures.Any(); }

        public async Task Initialize(FileActivatedEventArgs args)
            var file = args.Files[0];

            var folderPath = file.Path.Replace(file.Name, string.Empty);
            var folder = await StorageFolder.GetFolderFromPathAsync(folderPath);

            await SetPictures(await folder.GetFilesAsync());

When initializing the view model we take in file activation arguments (FileAcivatedEventArgs) which contain the path of the photo that was selected in Windows Explorer. Note that most IO APIs in WinRT are asynchronous by nature, hence the usage of async/await keywords. Based on the path being passed we determine the contaning folder and initialize our pictures collection with all photos from the same folder. The collection contains objects of PictureModel type which is a simple class containing information we need on the UI:

    internal class PictureModel : BindableBase
        private StorageFile _file;

        public PictureModel(StorageFile file)
            _file = file;

        public string UniqueId { 
            get { return _file.Path; } 

        private BitmapImage _image;
        public BitmapImage Image
            get { return _image; }

        public async Task Initialize()
            var fileStream = await _file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            BitmapImage bmp = new BitmapImage();
            _image = bmp;

The bit that is important is in Initialize method – you have to initialize BitmapImage from a file stream, if you don’t you will end up with a page but no image.

Now that we have all the code we only need to create some XAML to display the information. And here is how it will look like:

            AutomationProperties.Name="Item Details"
            ItemsSource="{Binding Pictures}">

                <Style TargetType="FlipViewItem">
                    <Setter Property="Margin" Value="0,0,0,0"/>


                        UserControl chosen as the templated item because it supports visual state management
                        Loaded/unloaded events explicitly subscribe to view state updates from the page
                    <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
                            <Image Height="Auto"
                                   Source="{Binding Image}">


                            <!-- Visual states reflect the application's view state inside the FlipView -->
                            <VisualStateGroup x:Name="ApplicationViewStates">
                                <VisualState x:Name="FullScreenLandscape"/>
                                <VisualState x:Name="Filled"/>

                                <!-- Respect the narrower 100-pixel margin convention for portrait -->
                                <VisualState x:Name="FullScreenPortrait">
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="Margin">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="97,20,87,67"/>

                                <!-- When snapped, the content is reformatted and scrolls vertically -->
                                <VisualState x:Name="Snapped">
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="Margin">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="17,20,17,67"/>


FlipView is a perfect control for what we are trying to achieve as it allows us to flip through items in our folder. A few things to notice here:

  • ItemsSource is bound to Pictures property of our FolderViewModel,
  • FlipView’s DataTemplate contains an Image control whose Source is bound to Image property of PictureModel class.


This is it. Running the app from Visual studio will only display a warning that no pictures could be found, but if you go to Windows Explorer and right click on a photo in Pictures library you should see an option to open it with PhotoViewer. Overall it is a very basic app, but it is a good start. Complete source code of this tutorial is on GitHub.