<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Diary of a Windows developer</title>
	<atom:link href="https://www.qmatteoq.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.qmatteoq.com</link>
	<description>Windows, mobile and much more</description>
	<lastBuildDate>Wed, 08 Nov 2023 18:32:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.8</generator>
	<item>
		<title>Moving my blog to a new home</title>
		<link>https://www.qmatteoq.com/moving-my-blog-to-a-new-home/</link>
					<comments>https://www.qmatteoq.com/moving-my-blog-to-a-new-home/#respond</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 06 Nov 2023 16:48:42 +0000</pubDate>
				<category><![CDATA[Developer's life]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=12905</guid>

					<description><![CDATA[It&#8217;s been a while since I posted on this blog! Not because I stopped blogging or caring about the community, but in the past year I focused my efforts on publishing new content and articles in the Tech Community website &#8230; <a href="https://www.qmatteoq.com/moving-my-blog-to-a-new-home/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[
<p>It&#8217;s been a while since I posted on this blog! Not because I stopped blogging or caring about the community, but in the past year I focused my efforts on publishing new content and articles in the<a href="https://aka.ms/appconsultblog"> Tech Community website</a> of my team at Microsoft.</p>



<p>Over time, I started to work on many different technologies. This blog started with Windows developer content, then I moved into the Microsoft 365 ecosystem, and I&#8217;ve started to share articles around building apps for Teams, add-ins for Microsoft 365 apps, etc.</p>



<p>Now, like many other colleagues, I&#8217;m supporting the AI motion in Microsoft, focusing mostly on Microsoft 365 and Copilot. To mark the occasion, I decided it was about time to reboot my blog and start sharing again my learnings using my own platform. As <a href="https://www.hanselman.com/">Scott Hanselman</a> often shares, owning your content is the best way to make sure that it doesn&#8217;t disappear if your blogging platform of choice goes out of the market. As such, I decided to reboot my blog not only from a content perspective, but starting from scratch: new technology, new name.</p>



<p>Please welcome <a href="https://www.developerscantina.com">The Developer&#8217;s Cantina</a> (yeah, I&#8217;m a big Star War fan)!</p>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="1024" src="https://blog.qmatteoq.com/wp-content/uploads/2023/11/circle_logo.png" alt="" class="wp-image-12906" style="width:390px;height:390px" srcset="http://www.qmatteoq.com/wp-content/uploads/2023/11/circle_logo.png 1024w, http://www.qmatteoq.com/wp-content/uploads/2023/11/circle_logo-300x300.png 300w, http://www.qmatteoq.com/wp-content/uploads/2023/11/circle_logo-150x150.png 150w, http://www.qmatteoq.com/wp-content/uploads/2023/11/circle_logo-768x768.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>The new blog is based on <a href="https://gohugo.io/">Hugo</a>, which is a static blogging platform hosted on Azure Static Web App. This means that my posts are simply made by Markdown files, which are stored on my hard disk. Whenever I want to publish a post, I simply commit a new Markdown file (and the related images, if I have them) into a GitHub repository. A GitHub Action generated by Azure does all the heavy work, by compiling the content of the repository into static web content (HTML, CSS and a little JavaScript), which is then served via HTTPS.</p>



<p>The choice of this platform gives me a few advantages:</p>



<ul>
<li>Since the posts are simply Markdown files, I can store them anywhere. If at any point in time I should decide to move away from Azure Static Web App, I just need to change the GitHub Action to point to another platform.</li>



<li>If I need to recover my content, I don&#8217;t need to host a blog platform first to read it. I can just open the Markdown files with Visual Studio Code or any other editor.</li>



<li>There is no database or server-side code, everything is static and running on the client. As such, the blog is super-fast.</li>
</ul>



<p>For the moment, this old blog will stay online, even if most of the content on is now outdated. I still haven&#8217;t made up my mind if migrating it to the new blog. Technically it&#8217;s doable, there&#8217;s a handy tool to convert content from WordPress to Hugo (or, for what matters,<a href="https://gohugo.io/tools/migrations/"> for almost any blogging platform</a>), but I still need to evaluate if it makes sense from a &#8220;quality&#8221; perspective.</p>



<p>Thanks to everyone who visited my old blog so far, I hope I will see you in <a href="https://www.developerscantina.com">The Developer&#8217;s Cantina</a>!</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/moving-my-blog-to-a-new-home/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Prism for Xamarin Forms &#8211; Handling platform specific code (Part 4)</title>
		<link>https://www.qmatteoq.com/prism-for-xamarin-forms-handling-platform-specific-code-part-4/</link>
					<comments>https://www.qmatteoq.com/prism-for-xamarin-forms-handling-platform-specific-code-part-4/#comments</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Thu, 01 Sep 2016 14:00:00 +0000</pubDate>
				<category><![CDATA[Xamarin]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Xamarin Forms]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=6616</guid>

					<description><![CDATA[Xamarin Forms is cool because it allows to share not just the business logic but also the user interface, unlike the traditional Xamarin approach, which requires to create multiple projects with its own user experience and features. However, at some &#8230; <a href="https://www.qmatteoq.com/prism-for-xamarin-forms-handling-platform-specific-code-part-4/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Xamarin Forms is cool because it allows to share not just the business logic but also the user interface, unlike the traditional Xamarin approach, which requires to create multiple projects with its own user experience and features. However, at some point, even with Xamarin Forms you have to deal with platform specific code: unless your application leverages only plain and simple features that can be embedded into a PCL (like in the sample project we’ve created in the <a href="http://blog.qmatteoq.com/?p=6585" target="_blank">previous posts</a>, where we simply downloaded some data from a REST API and we displayed it to the user), sooner or later you will have to use a feature that requires to write code which is different based on the target platform. There are many samples of this scenario: one of the most common is geo localization. Android, iOS and Windows offer a way to geo localize the user, but every platform uses its own approach and APIs, so you can’t include them in the Portable Class Library, since these APIs aren’t shared among the platform.</p>
<p>Luckily, to make the developer’s life easier, Xamarin has created many plugins for the most common scenarios, like geo localization, file system access, network, etc. which are available on NuGet or GitHub (<a title="https://github.com/xamarin/XamarinComponents" href="https://github.com/xamarin/XamarinComponents">https://github.com/xamarin/XamarinComponents</a>)</p>
<p>However, not all the scenarios are covered, so it may easily happen that you are required to implement your own plugin. Xamarin Forms includes an infrastructure to handle this requirement in an easy way, based on a class called <strong>DependencyService</strong>. From a high level, here is how it works:</p>
<ol>
<li>In your PCL you create an interface, which describes the methods you want to use in your shared code (for example, you could create an interface called <strong>IGeolocatorService</strong> which offers a <strong>GetPosition()</strong> method to retrieve the current location of the user). However, since it’s an interface, it describes just the operations you want to perform, without actually implementing them.
<li>In every platform specific project, you create a class that implement this interface, using the actual APIs provided by the platform. This means that, for example, your Android project will contain an <strong>AndroidGeolocatorService</strong>, which will contain the actual implementation of the <strong>GetPosition()</strong> method using the Android APIs. These classes have to be decorated with a special attribute provided by Xamarin Forms called <strong>Dependency </strong>with, as parameter, a reference to the type of the class itself: </li>
</ol>
<pre class="brush: csharp;">[assembly: Dependency(typeof(AndroidGeolocatorService))]
namespace InfoSeries.Droid.Services
{
    public class AndroidGeolocatorService: IGeolocatorService
    {
        public async Coordinates GetPosition()
        {
            //implementation using Android APIs
        }
    }
}

</pre>
<p>Thanks to this attribute, you are now able to use the <strong>DependencyService</strong> class and the <strong>Get&lt;T&gt;() </strong>method (where <strong>T</strong> is the interface type) in your PCL to get the proper implementation of the service, based on the platform where the app is running. Consequently, let’s say that in your PCL you have, at some point, the following code:</p>
<pre class="brush: csharp;">IGeolocatorService service = DependencyService.Get&lt;IGeolocatorService&gt;();
var result = service.GetPosition();
</pre>
<p>When the Xamarin Forms app is launched on an Android device, the <strong>Get&lt;IGeolocatorService&gt;()</strong> method will return an instance of the <strong>AndroidGeolocationService </strong>class; vice versa, if the app is launched on a Windows 10 device, the method will return an instance of the <strong>UwpGeolocationService</strong> class, which would have been created into the specific UWP project of the solution.</p>
<p>So far, so good. However, to reach this goal in our MVVM application, we would need to use the <strong>DependencyService</strong> class in a ViewModel, which isn’t a great approach: using a static property in a ViewModel makes things harder to test. Additionally, this approach would require us to use two different approaches based on the service type: </p>
<ol>
<li>If it’s a non platform specific service (like the <strong>TsApiService</strong> class we created in the previous posts to interact with the TrackSeries APIs), we register it into the Prism container and we let it automatically be injected into the ViewModel’s constructor.
<li>If it’s a platform specific service (like the previous <strong>AndroidGeolocatorService</strong> class), we have to access to it through the <strong>DependencyService</strong> class and not through the standard Prims container.</li>
</ol>
<p>With other MVVM frameworks, a typical workaround is to use the <strong>DependencyService</strong> in the framework’s bootstrapper to get the platform specific instance and then register it into the dependency container we’re using. This way, we can continue to leverage the usual approach to simply add a parameter in the ViewModel’s constructor and to have its implementation automatically injected. This is made possible by the fact that basically all the dependency containers allow to register not only a generic type (which means that, in this case, the container will create a new instance of the class when it’s requested) but also to assign a specific implementation to an interface.</p>
<p>Here is a sample code of how it would work:</p>
<pre class="brush: csharp;">protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation&lt;NavigationPage&gt;();
    Container.RegisterTypeForNavigation&lt;MainPage&gt;();
    Container.RegisterTypeForNavigation&lt;DetailPage&gt;();
    Container.RegisterType&lt;ITsApiService, TsApiService&gt;();

    var geoService = DependencyService.Get&lt;IGeolocationService&gt;();
    Container.RegisterInstance&lt;IGeolocationService&gt;(geoService);

}
</pre>
<p>However, Prism is smarter than that and it’s automatically able to register into its container every class he finds in each platform specific project decorated with the <strong>Dependency</strong> attribute. You can find a real example in the InfoSeries app on my GitHub repository: <a title="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries" href="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries">https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries</a></p>
<p>I’ve decided to implement a feature that allows a user to share, from within the detail page of a TV Show, the poster image of the show. This is something that needs to be implemented in a different way for each platform (since each of them has its own unique APIs to share content) and we can’t leverage an existing plugin (since the one available in the Xamarin repository supports only text sharing). As such, I’ve created in the Xamarin Forms Portable Class Library the following interface:</p>
<pre class="brush: csharp;">public interface IShareService
{
    Task SharePoster(string title, string image);
}
</pre>
<p>The interface simply describes an asynchronous method, called <strong>ShareShirt()</strong>, which accepts as parameter the title of the show and the path of the image to share. The next step is to implement this interface in every platform specific project. I won’t go into the details, because it would be out of scope for the post but, for example, here is how it looks the implementation in the Android project:</p>
<pre class="brush: csharp;">using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using InfoSeries.Droid.Services;
using InfoSeries.Services;
using Xamarin.Forms;
using Environment = Android.OS.Environment;

[assembly: Dependency(typeof(AndroidShareService))]
namespace InfoSeries.Droid.Services
{
    public class AndroidShareService: IShareService
    {
        public async Task SharePoster(string title, string image)
        {
            var intent = new Intent(Intent.ActionSend);
            intent.SetType("image/png");
            Guid guid = Guid.NewGuid();
            var path = Environment.GetExternalStoragePublicDirectory(Environment.DataDirectory
                                                                + Java.IO.File.Separator + guid + ".png");

            HttpClient client = new HttpClient();
            var httpResponse = await client.GetAsync(image);
            byte[] imageBuffer = await httpResponse.Content.ReadAsByteArrayAsync();

            if (File.Exists(path.AbsolutePath))
            {
                File.Delete(path.AbsolutePath);
            }

            using (var os = new System.IO.FileStream(path.AbsolutePath, System.IO.FileMode.Create))
            {
                await os.WriteAsync(imageBuffer, 0, imageBuffer.Length);
            }

            intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path));

            var intentChooser = Intent.CreateChooser(intent, "Share via");

            Activity activity = Forms.Context as Activity;
            activity.StartActivityForResult(intentChooser, 100);
        }
    }
}
</pre>
<p>As you can see, the class implements the <strong>ShareShirt() </strong>method by downloading the poster image in the local storage of the app and then, by using specific Android APIs (like <strong>Activity</strong> or <strong>Intent</strong>), it starts the sharing operation. As you can see, the class is decorated with the <strong>Dependency</strong> attribute with, as parameter, the type of the class itself.</p>
<p>Thanks to Prism, that’s all we need to do. Now simply add, in the <strong>DetailPageViewModel, </strong>a parameter of type <strong>IShareService </strong>in the class constructor, so that you can use it the command that will be invoked when the user will press the button to share the image. Here is how our updated <strong>DetailPageViewModel</strong> looks like:</p>
<pre class="brush: csharp;">public class DetailPageViewModel : BindableBase, INavigationAware
{
    private readonly IShareService _shareService;
    private SerieFollowersVM _selectedShow;

    public SerieFollowersVM SelectedShow
    {
        get { return _selectedShow; }
        set { SetProperty(ref _selectedShow, value); }
    }

    public DetailPageViewModel(IShareService shareService)
    {
        _shareService = shareService;
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public void OnNavigatedTo(NavigationParameters parameters)
    {
        SelectedShow = parameters["show"] as SerieFollowersVM;
    }

    private DelegateCommand _shareItemCommand;

    public DelegateCommand ShareItemCommand
    {
        get
        {
            if (_shareItemCommand == null)
            {
                _shareItemCommand = new DelegateCommand(async () =&gt;
                {
                    string image = SelectedShow.Images.Poster;
                    await _shareService.SharePoster(SelectedShow.Name, image);
                });
            }

            return _shareItemCommand;
        }
    }
}
</pre>
<p>We have added an <strong>IShareService</strong> parameter in the constructor and we have defined a <strong>DelegateCommand</strong> called <strong>ShareItemCommand</strong>: when it’s invoked, it will simply call the <strong>ShareShirt()</strong> method exposed by the <strong>IShareService</strong> interface, passing as parameter the name of the show and the URL of the poster image (which can be both retrieved from the <strong>SelectedShow</strong> property).</p>
<p>In the end, in the<strong> DetailPage.xaml </strong>we have added a <strong>ToolbarItem</strong> control, which adds a new button in the UI’s toolbar (which is rendered in a different way based on the platform, for example on UWP it’s rendered as a button in the <strong>CommandBar</strong>):</p>
<pre class="brush: xml;">&lt;ContentPage.ToolbarItems&gt;
  &lt;ToolbarItem Text="Share" Command="{Binding Path=ShareItemCommand}" Order="Secondary"/&gt;
&lt;/ContentPage.ToolbarItems&gt;
</pre>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-14-46-47.png"><img decoding="async" title="Screenshot_2016-08-22-14-46-47" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-22-14-46-47" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-14-46-47_thumb.png" width="290" height="516"></a></td>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-14-46-38.png"><img decoding="async" title="Screenshot_2016-08-22-14-46-38" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-22-14-46-38" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-14-46-38_thumb.png" width="290" height="516"></a></td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Nothing special here: the control has a text and it’s connected through binding to the <strong>ShareItemCommand</strong> we have previously defined in the ViewModel. Now launch the application on an Android device or emulator, choose one TV Show and use the new share option we’ve just added: automagically, Android will show us the share chooser, which will allow the user to choose which target application will receive the image. As you can see, we didn’t have to register anything related to the <strong>IShareService</strong> in the <strong>App </strong>class: Prism did everything on its own. Of course, if we want to achieve the same result also when the app is running on iOS or on Windows 10, we need to create also an implementation of the <strong>IShareService</strong> interface in the other platform specific projects.</p>
<p>Pretty cool, isn’t it?</p>
<h3></h3>
<h3>Wrapping up</h3>
<p>We have concluded our journey in learning how the most recent version of the Prism framework has been greatly improved, specifically when it comes to support Xamarin Forms. Thanks to Prism and Xamarin, it will be much easier to create great cross platform application using the MVVM pattern and leveraging the same skills you have learned as a developer by creating WPF, Silverlight, Windows Store or UWP apps. As a final reminder, don’t forger that all the samples used in this series of posts are available on my GitHub account: <a title="https://github.com/qmatteoq/XamarinForms-Prism" href="https://github.com/qmatteoq/XamarinForms-Prism">https://github.com/qmatteoq/XamarinForms-Prism</a></p>
<p>Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/prism-for-xamarin-forms-handling-platform-specific-code-part-4/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Prism for Xamarin Forms &#8211; Advanced navigation (Part 3)</title>
		<link>https://www.qmatteoq.com/prism-for-xamarin-forms-advanced-navigation-part-3/</link>
					<comments>https://www.qmatteoq.com/prism-for-xamarin-forms-advanced-navigation-part-3/#comments</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 29 Aug 2016 14:00:00 +0000</pubDate>
				<category><![CDATA[Xamarin]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Xamarin Forms]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=6608</guid>

					<description><![CDATA[In the previous post, we’ve expanded a bit our original sample application, by creating a service to interact with the APIs offered by the TrackSeries website, by using it to populate some data in the app and, in the end, &#8230; <a href="https://www.qmatteoq.com/prism-for-xamarin-forms-advanced-navigation-part-3/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In the previous post, we’ve expanded a bit our original sample application, by creating a service to interact with the APIs offered by the <a href="https://www.trackseries.tv/" target="_blank">TrackSeries</a> website, by using it to populate some data in the app and, in the end, by creating a detail page where to see more info about the selected show. This way, we have understood how Prism allows to manage some basic concepts like navigation, page’s lifecycle and dependency injection.</p>
<p>In this post we’re going to see a couple of more advanced concepts which, however, can be fundamental when it comes to develop a real project using Xamarin Forms.</p>
<h3>Advanced navigation</h3>
<p>If you have tested the previous version of the app, you would have noted some issues with navigation, especially if you have navigated to the detail page of a TV Show. For example, if you test the UWP version on a Windows 10 PC, you will notice that the Back button that is usually available in the top left corner of the chrome of the windows is missing. Or on Android or iOS, the navigation bar which shows the title of the page and the virtual back button is missing, so if your device doesn’t have an actual back button (like an iPhone), you don’t have a way to go back to the home once you are into a show detail page.</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-22-51-58.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-20-22-51-58" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-20-22-51-58" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-22-51-58_thumb.png" width="290" height="515"></a></p>
<p>If you have some previous experience with Xamarin Forms you should already have an idea why this problem is happening. Every basic page in a Xamarin Forms app is represented by the <strong>ContentPage</strong> class, but it can be embedded in other kind of pages to provide more advanced navigation scenarios, like a <strong>NavigationPage </strong>(to provide a navigation UI) or a <strong>TabbedPage</strong> (to show multiple pages in different tabs). In the sample we’ve created so far, we’ve just created two basic pages (of type <strong>ContentPage</strong>) and then we’ve simply navigated to them using the <strong>NavigationService</strong>. We haven’t specified anywhere that the pages should have been actually embedded into a <strong>NavigationPage</strong> to get access to the navigation UI.</p>
<p>To achieve this goal in a plain Xamarin Forms app, we would have done something like this:</p>
<pre class="brush: csharp;">public partial class App : Application
{
    public App()
    {
        MainPage = new NavigationPage(new MainPage());
    }     
}
</pre>
<p>An instance of the <strong>MainPage</strong> of the application is embedded into a new instance of a <strong>NavigationPage</strong>: from now on, the <strong>NavigationPage</strong> will be the container of each <strong>ContentPage</strong> that the user will see, providing a consistent navigation UI across every page of the app. However, with the Prism approach, we can’t recreate the same approach:</p>
<pre class="brush: csharp;">public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MainPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation&lt;MainPage&gt;();
        Container.RegisterTypeForNavigation&lt;DetailPage&gt;();
        Container.RegisterType&lt;ITsApiService, TsApiService&gt;();
    }
}
</pre>
<p>We have just registered, in the <strong>Container</strong>, the <strong>MainPage</strong> and then we have called the <strong>NavigateAsync()</strong> method of the <strong>NavigationService</strong>, which accepts only the key that identifies the destination page: we can’t specify, in any way, that this page should be embedded into a <strong>NavigationPage</strong>.</p>
<p>Luckily, Prism has a smart solution for this problem: deep linking. One of the features offered by Prism for Xamarin Forms, in fact, is to support complex queries as parameters of the <strong>NavigateAsync()</strong> method. For example, we can specify queries like “<strong>MainPage/DetailPage?id=1”</strong> to navigate directly to the detail page of the app and, at the same time, passing a parameter called <strong>id</strong> with value <strong>1. </strong>This approach is very useful when, for example, you want to link a specific page of your application from another application, a website or a section of your app.</p>
<p align="left">We can leverage this feature also to achieve the goal of embedding our pages into a <strong>NavigationPage: </strong>first, we need to register the base <strong>NavigationPage </strong>type included in Xamarin Forms as a type for navigation in the <strong>Container</strong>. Then, we can use the query <strong>“NavigationPage/MainPage”</strong> to tell to the <strong>NavigationService</strong> that we need to navigate first to the page identified by the <strong>NavigationPage</strong> key and then to the one identified by the <strong>MainPage</strong> key. Since the <strong>NavigationPage </strong>isn’t actually a real page, but just a container, the end result will be the same we’ve seen in the first sample code: the <strong>MainPage</strong> (and every consequent page in the navigation flow) will be embedded into a <strong>NavigationPage.</strong></p>
<p>Here is how our new <strong>App </strong>class looks like:</p>
<pre class="brush: csharp;">public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("NavigationPage/MainPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation&lt;NavigationPage&gt;();
        Container.RegisterTypeForNavigation&lt;MainPage&gt;();
        Container.RegisterTypeForNavigation&lt;DetailPage&gt;();
        Container.RegisterType&lt;ITsApiService, TsApiService&gt;();
    }
}
</pre>
<p>&nbsp;</p>
<p>Thanks to this change, now we have a proper navigation bar, as you can see in the following screenshot taken from the Android version:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-22-53-06.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-20-22-53-06" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-20-22-53-06" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-22-53-06_thumb.png" width="290" height="516"></a></p>
<p>Another example of complex deep linking is using query parameters. You can use a navigation query like the following one:</p>
<pre class="brush: csharp;">NavigationService.NavigateAsync("FirstPage?id=1&amp;title=First page");
</pre>
<p>Automatically, the destination page will receive, in the <strong>NavigationParams</strong> object of the <strong>OnNavigatedTo()</strong> method, two items: one with key <strong>id</strong> and value <strong>1</strong> and one with key <strong>title</strong> and value <strong>First page.</strong></p>
<pre class="brush: csharp;">public void OnNavigatedTo(NavigationParameters parameters)
{
    string id = parameters["id"].ToString();
    string title = parameters["title"].ToString();

    Title = $"Page with id {id} and title {title}";
}
</pre>
<p><strong></strong></p>
<p>Eventually, you can use this feature to leverage even more complex navigation flows, which involves container for multiple pages.</p>
<p>Let’s try to better understand this scenario with a real example. We have already talked about the concept that Xamarin Forms offers some pages which doesn’t display any actual content, but that they act as a container for other pages. We’ve already seen an example of this concept: the <strong>NavigationPage</strong> type doesn’t display any actual content, but it’s a container to add navigation UI and features to a <strong>ContentPage</strong>. Another similar container is <strong>TabbedPage</strong>, where every children page is displayed in a different tab.</p>
<p>Let’s say that we want to improve our TV show application and add two sections to the main page, using a <strong>TabbedPage</strong> control: the first section will display the list of upcoming shows, so it will be a simple <strong>ContentPage;</strong> the second section, instead, will display a list of the available TV Shows and, as such, it will be embedded into a <strong>NavigationPage, </strong>because we want to provide the ability to tap on a show and see more info about the selected show.</p>
<p>This is how our project would look like:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism4.png"><img loading="lazy" decoding="async" title="prism4" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="prism4" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism4_thumb.png" width="430" height="319"></a></p>
<p>The application has two main sections (<strong>UpcomingShowsPage </strong>and <strong>ShowsListPage</strong>) and a detail page (<strong>DetailPage</strong>), each of them with its own ViewModel. The main pages are presented to the user as two sections of a tab control, which is defined in the <strong>MainTabbedPage.xaml</strong> file:</p>
<pre class="brush: csharp;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
            xmlns:views="clr-namespace:PrismTest.Views;assembly=PrismTest"
            prism:ViewModelLocator.AutowireViewModel="True"
            Title="Main page"
            x:Class="PrismTest.Views.MainTabbedPage"&gt;

  &lt;views:UpcomingShowsPage /&gt;
  &lt;NavigationPage Title="Shows list"&gt;
    &lt;x:Arguments&gt;
      &lt;views:ShowsListPage /&gt;
    &lt;/x:Arguments&gt;
  &lt;/NavigationPage&gt;

&lt;/TabbedPage&gt;
</pre>
<p>The <strong>UpcomingShowsPage</strong> is a simple <strong>ContentPage</strong>, while the <strong>ShowsListPsage </strong>is embedded into a<strong> NavigationPage</strong>, since the user has the chance to move to the <strong>DetailPage</strong> to see more info about the selected TV show. Now let’s say that, as a consequence of an user action, we want to redirect the user to the detail page of a specific TV Show.&nbsp; With standard Xamarin Forms it wouldn’t a hard task to accomplish, but the real challenge would be to retain the whole navigation stack: we want to bring the user to the detail page, but we also want that, when he presses the back button, he follows the proper backward navigation flow (so <strong>DetailPage –&gt; ShowListPage</strong>). Additionally, everything should be done by keeping the focus in the second tab, since <strong>ShowListPage </strong>is part of a <strong>TabbedPage</strong>.</p>
<p>Sounds complicated, isn&#8217;t it? Well, here is how it’s easy to achieve this goal with Prism:</p>
<pre class="brush: csharp;">public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MainTabbedPage/NavigationPage/ShowsListPage/DetailPage?id=1");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation&lt;UpcomingShowsPage&gt;();
        Container.RegisterTypeForNavigation&lt;ShowsListPage&gt;();
        Container.RegisterTypeForNavigation&lt;DetailPage&gt;();
        Container.RegisterTypeForNavigation&lt;MainTabbedPage&gt;();
        Container.RegisterTypeForNavigation&lt;NavigationPage&gt;();
    }
}
</pre>
<pre class="brush: csharp;"></pre>
<p>As usual, in the <strong>RegisterTypes()</strong> method, we have registered every page that compose our application. Then, we invoke the <strong>NavigateAsync()</strong> method of the <strong>NavigationService</strong> passing the whole path we want to follow: <strong>MainTabbedPage/NavigationPage/ShowsListPage/DetailPage</strong> with an additional parameter that identifies the selected TV Show, that we can intercept in the <strong>OnNavigatedTo() </strong>method of the<strong> DetailPageViewModel</strong>.</p>
<pre class="brush: csharp;">public class DetailPageViewModel : BindableBase, INavigationAware
{
    private readonly ITsApiService _tsApiService;
    private SerieInfoVM _selectedShow;

    public SerieInfoVM SelectedShow
    {
        get { return _selectedShow; }
        set { SetProperty(ref _selectedShow, value); }
    }

    public DetailPageViewModel(ITsApiService tsApiService)
    {
        _tsApiService = tsApiService;
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public async void OnNavigatedTo(NavigationParameters parameters)
    {
        int id = Convert.ToInt32(parameters["id"]);
        SelectedShow = await _tsApiService.GetSerieById(id);
    }
}
</pre>
<p>Thanks to Prism, other than achieving the goal of redirecting the user directly to the page we’re interested into, we have also retained the full backward navigation stack. The following images show you what happens when you press the Back button:</p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-11-40-17.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-22-11-40-17" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="Screenshot_2016-08-22-11-40-17" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-11-40-17_thumb.png" width="290" height="516"></a></td>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-11-42-41.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-22-11-42-41" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="Screenshot_2016-08-22-11-42-41" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-22-11-42-41_thumb.png" width="290" height="516"></a></td>
</tr>
</tbody>
</table>
<p>As you can see, from the detail page of the show (the screenshot on the left) we’ve been properly redirected to the previous page in the stack (the shows list, displayed in the screenshot on the right), even if we didn’t actually visited it during our navigation flow (since the app was directly loaded in the detail page). Additionally, we’ve kept the focus on the second tab (<strong>Shows list</strong>) so the user has still the chance, at any time, to move to the first one (<strong>Upcoming shows</strong>). Pretty cool, isn’t it?</p>
<p><strong>Attention</strong>: in the current Prism implementation dealing with the <strong>TabbedPage</strong> control has a downside. In our example, as we’ve seen from the screenshot of the project’s structure, the Upcoming Shows section is represented by a standard page (<strong>UpcomingShowsPage</strong>) with its own ViewModel (<strong>UpcomingShowsPageViewModel</strong>), which implements the <strong>INavigationAware</strong> interface with the goal to leverage the <strong>OnNavigatedTo()</strong> method to load the data (in our case, the list of upcoming shows). As such, the <strong>UpcomingShowsPageViewModel</strong> would look like this:</p>
<pre class="brush: csharp;">public class UpcomingShowsPageViewModel : BindableBase, INavigationAware
{
    private readonly ITsApiService _tsApiService;

    private ObservableCollection&lt;SerieFollowersVM&gt; _topSeries;

    public ObservableCollection&lt;SerieFollowersVM&gt; TopSeries
    {
        get { return _topSeries; }
        set { SetProperty(ref _topSeries, value); }
    }

    public UpcomingShowsPageViewModel(ITsApiService tsApiService)
    {
        _tsApiService = tsApiService;
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public async void OnNavigatedTo(NavigationParameters parameters)
    {
        var series = await _tsApiService.GetStatsTopSeries();
        TopSeries = new ObservableCollection&lt;SerieFollowersVM&gt;(series);
    }
}
</pre>
<p>However, if you tap on the <strong>Upcoming Shows</strong> tab you’ll notice that nothing won’t happen and the <strong>OnNavigatedTo()</strong> method won’t be triggered. The reason is that the navigation methods implemented by the <strong>INavigationAware</strong> interface are raised only when you navigate using the Prism <strong>NavigationService</strong>. If the navigation happens without leveraging it (like, in this case, where the navigation to the other tab is handled directly by the Xamarin Forms infrastructure), the <strong>OnNavigatedTo()</strong> method in the ViewModel will never be invoked and, as such, our data will never be loaded. There’s a solution in the works, which involves using a behavior, but it hasn’t been included yet in the current Prism version. You can follow the discussion and the proposed solution on GitHub: <a title="https://github.com/PrismLibrary/Prism/issues/650" href="https://github.com/PrismLibrary/Prism/issues/650">https://github.com/PrismLibrary/Prism/issues/650</a></p>
<h2></h2>
<h3>Wrapping up</h3>
<p>In this post we’ve learned how to leverage the deep linking featured offered by Prism, which allows to handle complex navigation patterns in an easy way, keeping at the same time the proper backward navigation path. In the next post (which will be the last one), we’ll see instead how to use platform specific code in a Xamarin Forms application created with Prism. You can find all the samples on my GitHub repository: the InfoSeries one (<a title="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries" href="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries">https://github.com/qmatteoq/XamarinForms-Prism/tree/master/InfoSeries</a>) shows you the first approach (simple navigation using a NavigationPage), the DeepNavigation one (<a title="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/DeepNavigation" href="https://github.com/qmatteoq/XamarinForms-Prism/tree/master/DeepNavigation">https://github.com/qmatteoq/XamarinForms-Prism/tree/master/DeepNavigation</a>) instead shows you the advanced deep link feature we’ve seen in the second part of the post. Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/prism-for-xamarin-forms-advanced-navigation-part-3/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Prism for Xamarin Forms &#8211; Basic navigation and dependency injection (Part 2)</title>
		<link>https://www.qmatteoq.com/prism-for-xamarin-forms-basic-navigation-and-dependency-injection-part-2/</link>
					<comments>https://www.qmatteoq.com/prism-for-xamarin-forms-basic-navigation-and-dependency-injection-part-2/#respond</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Thu, 25 Aug 2016 14:00:00 +0000</pubDate>
				<category><![CDATA[Xamarin]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Xamarin Forms]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=6585</guid>

					<description><![CDATA[In the previous post we’ve started to see the basic concepts on how to leverage the new version of Prism (6.2) to implement the MVVM pattern in a Xamarin Forms app. So far, we haven’t seen nothing special that we &#8230; <a href="https://www.qmatteoq.com/prism-for-xamarin-forms-basic-navigation-and-dependency-injection-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><a href="http://blog.qmatteoq.com/?p=6582" target="_blank">In the previous post</a> we’ve started to see the basic concepts on how to leverage the new version of Prism (6.2) to implement the MVVM pattern in a Xamarin Forms app. So far, we haven’t seen nothing special that we couldn’t do also with another framework: we have just created a View, a ViewModel and we connected them through binding. In this post, we’re going to see how Prism can be helpful to handle a very common scenario which can be hard to handle in a MVVM app: navigation and page’s lifecycle.</p>
<p>As we’ve mentioned in the previous post, we’re going to create a simple client for <a href="https://www.trackseries.tv/" target="_blank">TrackSeries</a>, a website which offers many information about TV Shows. The app will display the current top series and will allow the user to discover more about them. To achieve this goal, we can use a set of REST services provided by the website, which are very simple to use and which follow the standard best practices of dealing with REST services: you invoke a URL using a HTTP command and you receive back a JSON response with the result.</p>
<p>For example, if you want to know which are the top series at the moment, you can just perform a HTTP GET request to the following URL: <a title="https://api.trackseries.tv/v1/Stats/TopSeries" href="https://api.trackseries.tv/v1/Stats/TopSeries">https://api.trackseries.tv/v1/Stats/TopSeries</a> The service will return you a JSON response with all the details about the top series:</p>
<pre class="brush: js;">[
   {
      "id":121361,
      "name":"Game of Thrones",
      "followers":10230,
      "firstAired":"2011-04-17T21:00:00-04:00",
      "country":"us",
      "overview":"Seven noble families fight for control of the mythical land of Westeros. Friction between the houses leads to full-scale war. All while a very ancient evil awakens in the farthest north. Amidst the war, a neglected military order of misfits, the Night's Watch, is all that stands between the realms of men and the icy horrors beyond.",
      "runtime":55,
      "status":"Continuing",
      "network":"HBO",
      "airDay":"Sunday",
      "airTime":"9:00 PM",
      "contentRating":"TV-MA",
      "imdbId":"tt0944947",
      "tvdbId":121361,
      "tmdbId":1399,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/121361-49.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/121361-15.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/121361-g22.jpg"
      },
      "genres":[
         {
            "id":2,
            "name":"Adventure"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":5,
            "name":"Fantasy"
         }
      ],
      "added":"2014-08-08T13:30:46.227",
      "lastUpdated":"2016-08-18T03:03:50.05",
      "followedByUser":false,
      "slugName":"game-of-thrones"
   },
   {
      "id":257655,
      "name":"Arrow",
      "followers":7517,
      "firstAired":"2012-10-10T20:00:00-04:00",
      "country":"us",
      "overview":"Oliver Queen and his father are lost at sea when their luxury yacht sinks. His father doesn't survive. Oliver survives on an uncharted island for five years learning to fight, but also learning about his father's corruption and unscrupulous business dealings. He returns to civilization a changed man, determined to put things right. He disguises himself with the hood of one of his mysterious island mentors, arms himself with a bow and sets about hunting down the men and women who have corrupted his city.",
      "runtime":45,
      "status":"Continuing",
      "network":"The CW",
      "airDay":"Wednesday",
      "airTime":"8:00 PM",
      "contentRating":"TV-14",
      "imdbId":"tt2193021",
      "tvdbId":257655,
      "tmdbId":1412,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/257655-8.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/257655-47.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/257655-g9.jpg"
      },
      "genres":[
         {
            "id":1,
            "name":"Action"
         },
         {
            "id":2,
            "name":"Adventure"
         },
         {
            "id":4,
            "name":"Drama"
         }
      ],
      "added":"2014-08-08T13:37:00.133",
      "lastUpdated":"2016-08-15T03:11:32.013",
      "followedByUser":false,
      "slugName":"arrow"
   },
   {
      "id":153021,
      "name":"The Walking Dead",
      "followers":7185,
      "firstAired":"2010-10-31T21:00:00-04:00",
      "country":"us",
      "overview":"The world we knew is gone. An epidemic of apocalyptic proportions has swept the globe causing the dead to rise and feed on the living. In a matter of months society has crumbled. In a world ruled by the dead, we are forced to finally start living. Based on a comic book series of the same name by Robert Kirkman, this AMC project focuses on the world after a zombie apocalypse. The series follows a police officer, Rick Grimes, who wakes up from a coma to find the world ravaged with zombies. Looking for his family, he and a group of survivors attempt to battle against the zombies in order to stay alive.\n",
      "runtime":50,
      "status":"Continuing",
      "network":"AMC",
      "airDay":"Sunday",
      "airTime":"9:00 PM",
      "contentRating":"TV-MA",
      "imdbId":"tt1520211",
      "tvdbId":153021,
      "tmdbId":1402,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/153021-38.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/153021-77.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/153021-g44.jpg"
      },
      "genres":[
         {
            "id":1,
            "name":"Action"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":6,
            "name":"Horror"
         },
         {
            "id":20,
            "name":"Suspense"
         }
      ],
      "added":"2014-08-08T13:31:18.617",
      "lastUpdated":"2016-08-18T03:04:00.28",
      "followedByUser":false,
      "slugName":"the-walking-dead"
   },
   {
      "id":279121,
      "name":"The Flash (2014)",
      "followers":7069,
      "firstAired":"2014-10-07T20:00:00-04:00",
      "country":"us",
      "overview":"After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion – and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become... The Flash.",
      "runtime":45,
      "status":"Continuing",
      "network":"The CW",
      "airDay":"Tuesday",
      "airTime":"8:00 PM",
      "contentRating":"TV-14",
      "imdbId":"tt3107288",
      "tvdbId":279121,
      "tmdbId":60735,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/279121-37.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/279121-23.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/279121-g7.jpg"
      },
      "genres":[
         {
            "id":1,
            "name":"Action"
         },
         {
            "id":2,
            "name":"Adventure"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":8,
            "name":"Science-Fiction"
         }
      ],
      "added":"2014-08-08T13:45:59.087",
      "lastUpdated":"2016-08-17T03:09:18.7",
      "followedByUser":false,
      "slugName":"the-flash-2014"
   },
   {
      "id":80379,
      "name":"The Big Bang Theory",
      "followers":6922,
      "firstAired":"2007-09-25T20:00:00-04:00",
      "country":"us",
      "overview":"What happens when hyperintelligent roommates Sheldon and Leonard meet Penny, a free-spirited beauty moving in next door, and realize they know next to nothing about life outside of the lab. Rounding out the crew are the smarmy Wolowitz, who thinks he's as sexy as he is brainy, and Koothrappali, who suffers from an inability to speak in the presence of a woman.",
      "runtime":25,
      "status":"Continuing",
      "network":"CBS",
      "airDay":"Monday",
      "airTime":"8:00 PM",
      "contentRating":"TV-PG",
      "imdbId":"tt0898266",
      "tvdbId":80379,
      "tmdbId":1418,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/80379-43.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/80379-38.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/80379-g28.jpg"
      },
      "genres":[
         {
            "id":3,
            "name":"Comedy"
         }
      ],
      "added":"2014-08-08T13:27:13.18",
      "lastUpdated":"2016-08-18T03:03:10.947",
      "followedByUser":false,
      "slugName":"the-big-bang-theory"
   },
   {
      "id":176941,
      "name":"Sherlock",
      "followers":6387,
      "firstAired":"2010-07-25T20:30:00+01:00",
      "country":"gb",
      "overview":"Sherlock is a British television crime drama that presents a contemporary adaptation of Sir Arthur Conan Doyle's Sherlock Holmes detective stories. Created by Steven Moffat and Mark Gatiss, it stars Benedict Cumberbatch as Sherlock Holmes and Martin Freeman as Doctor John Watson.",
      "runtime":90,
      "status":"Continuing",
      "network":"BBC One",
      "airDay":"Sunday",
      "airTime":"8:30 PM",
      "contentRating":"TV-14",
      "imdbId":"tt1475582",
      "tvdbId":176941,
      "tmdbId":19885,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/176941-11.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/176941-3.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/176941-g5.jpg"
      },
      "genres":[
         {
            "id":2,
            "name":"Adventure"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":14,
            "name":"Crime"
         },
         {
            "id":16,
            "name":"Mystery"
         },
         {
            "id":21,
            "name":"Thriller"
         }
      ],
      "added":"2014-08-08T13:32:27.247",
      "lastUpdated":"2016-08-17T03:07:09.747",
      "followedByUser":false,
      "slugName":"sherlock"
   },
   {
      "id":263365,
      "name":"Marvel's Agents of S.H.I.E.L.D.",
      "followers":5372,
      "firstAired":"2013-09-24T22:00:00-04:00",
      "country":"us",
      "overview":"Phil Coulson (Clark Gregg, reprising his role from \"The Avengers\" and \"Iron Man\" ) heads an elite team of fellow agents with the worldwide law-enforcement organization known as SHIELD (Strategic Homeland Intervention Enforcement and Logistics Division), as they investigate strange occurrences around the globe. Its members -- each of whom brings a specialty to the group -- work with Coulson to protect those who cannot protect themselves from extraordinary and inconceivable threats, including a formidable group known as Hydra.",
      "runtime":45,
      "status":"Continuing",
      "network":"ABC (US)",
      "airDay":"Tuesday",
      "airTime":"10:00 PM",
      "contentRating":"TV-PG",
      "imdbId":"tt2364582",
      "tvdbId":263365,
      "tmdbId":1403,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/263365-16.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/263365-26.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/263365-g7.jpg"
      },
      "genres":[
         {
            "id":1,
            "name":"Action"
         },
         {
            "id":2,
            "name":"Adventure"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":5,
            "name":"Fantasy"
         },
         {
            "id":8,
            "name":"Science-Fiction"
         }
      ],
      "added":"2014-08-08T13:39:45.967",
      "lastUpdated":"2016-08-18T03:05:30.987",
      "followedByUser":false,
      "slugName":"marvels-agents-of-shield"
   },
   {
      "id":81189,
      "name":"Breaking Bad",
      "followers":5227,
      "firstAired":"2008-01-20T21:00:00-04:00",
      "country":"us",
      "overview":"Walter White, a struggling high school chemistry teacher, is diagnosed with advanced lung cancer. He turns to a life of crime, producing and selling methamphetamine accompanied by a former student, Jesse Pinkman, with the aim of securing his family's financial future before he dies.",
      "runtime":45,
      "status":"Ended",
      "network":"AMC",
      "airDay":"Sunday",
      "airTime":"9:00 PM",
      "contentRating":"TV-MA",
      "imdbId":"tt0903747",
      "tvdbId":81189,
      "tmdbId":1396,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/81189-10.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/81189-21.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/81189-g21.jpg"
      },
      "genres":[
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":14,
            "name":"Crime"
         },
         {
            "id":20,
            "name":"Suspense"
         },
         {
            "id":21,
            "name":"Thriller"
         }
      ],
      "added":"2014-08-08T13:27:33.917",
      "lastUpdated":"2016-08-13T03:01:47.063",
      "followedByUser":false,
      "slugName":"breaking-bad"
   },
   {
      "id":247808,
      "name":"Suits",
      "followers":4835,
      "firstAired":"2011-06-24T21:00:00-04:00",
      "country":"us",
      "overview":"Suits follows college drop-out Mike Ross, who accidentally lands a job with one of New York's best legal closers, Harvey Specter. They soon become a winning team with Mike's raw talent and photographic memory, and Mike soon reminds Harvey of why he went into the field of law in the first place.",
      "runtime":45,
      "status":"Continuing",
      "network":"USA Network",
      "airDay":"Wednesday",
      "airTime":"9:00 PM",
      "contentRating":"TV-14",
      "imdbId":"tt1632701",
      "tvdbId":247808,
      "tmdbId":37680,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/247808-27.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/247808-43.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/247808-g17.jpg"
      },
      "genres":[
         {
            "id":4,
            "name":"Drama"
         }
      ],
      "added":"2014-08-08T13:33:45.423",
      "lastUpdated":"2016-08-18T03:04:21.37",
      "followedByUser":false,
      "slugName":"suits"
   },
   {
      "id":274431,
      "name":"Gotham",
      "followers":4718,
      "firstAired":"2014-09-23T20:00:00-04:00",
      "country":"us",
      "overview":"An action-drama series following rookie detective James Gordon as he battles villains and corruption in pre-Batman Gotham City.",
      "runtime":45,
      "status":"Continuing",
      "network":"FOX (US)",
      "airDay":"Monday",
      "airTime":"8:00 PM",
      "contentRating":"TV-14",
      "imdbId":"tt3749900",
      "tvdbId":274431,
      "tmdbId":60708,
      "language":"en",
      "images":{
         "poster":"http://static.trackseries.tv/banners/posters/274431-17.jpg",
         "fanart":"http://static.trackseries.tv/banners/fanart/original/274431-22.jpg",
         "banner":"http://static.trackseries.tv/banners/graphical/274431-g6.jpg"
      },
      "genres":[
         {
            "id":1,
            "name":"Action"
         },
         {
            "id":4,
            "name":"Drama"
         },
         {
            "id":8,
            "name":"Science-Fiction"
         },
         {
            "id":14,
            "name":"Crime"
         },
         {
            "id":21,
            "name":"Thriller"
         }
      ],
      "added":"2014-08-08T13:44:55.4",
      "lastUpdated":"2016-08-17T03:08:55.473",
      "followedByUser":false,
      "slugName":"gotham"
   }
]
</pre>
<p>To use these APIs in the application, I’ve created a class called <strong>TsApiService</strong> with a set of methods that, by using the <strong>HttpClient</strong> class of the .NET Framework and the popular JSON.NET library, takes care of downloading the JSON, parsing it and returning a set of objects that can be easily manipulated using C#. To structure my solution in a better way, I’ve decided to place all the classes related to the communication with the REST APIs (like services and entities) in another Portable Class Library, called <strong>InfoSeries.Core</strong>, which is a different PCL than the one that hosts the real Xamarin Forms app.</p>
<p>Here is, for example, how the method that takes care of parsing the previous JSON and to return a list of C# objects looks like:</p>
<pre class="brush: csharp;">public async Task&lt;List&lt;SerieFollowersVM&gt;&gt; GetStatsTopSeries()
{
    using (HttpClient client = new HttpClient())
    {
        try
        {
            var response = await client.GetAsync("https://api.trackseries.tv/v1/Stats/TopSeries");
            if (!response.IsSuccessStatusCode)
            {
                var error = await response.Content.ReadAsAsync&lt;TrackSeriesApiError&gt;();
                var message = error != null ? error.Message : "";
                throw new TrackSeriesApiException(message, response.StatusCode);
            }
            return await response.Content.ReadAsAsync&lt;List&lt;SerieFollowersVM&gt;&gt;();
        }
        catch (HttpRequestException ex)
        {
            throw new TrackSeriesApiException("", false, ex);
        }
        catch (UnsupportedMediaTypeException ex)
        {
            throw new TrackSeriesApiException("", false, ex);
        }
    }
}
</pre>
<p>The <strong>GetAsync()</strong> method of the <strong>HttpClient</strong> class performs a GET request to the URL, returning as result the string containing the JSON response. This result is stored into the <strong>Content</strong> property<strong> </strong>of the response: in case the request is successful (we use the <strong>IsSuccessStatusCode</strong> property to check this condition), we use the <strong>ReadAsAsync&lt;T&gt;</strong> method exposed by the <strong>Content</strong> property to automatically convert the JSON result in a collection of <strong>SerieFollowersVM</strong> object. <strong>SerieFollowersVM</strong> is nothing else than a class that maps each property of the JSON response (like <strong>name</strong>, <strong>country</strong> or <strong>runtime</strong>) into a C# property:</p>
<pre class="brush: csharp;">public class SerieFollowersVM
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Followers { get; set; }
    public DateTimeOffset FirstAired { get; set; }
    public string Country { get; set; }
    public string Overview { get; set; }
    public int Runtime { get; set; }
    public string Status { get; set; }
    public string Network { get; set; }
    public DayOfWeek? AirDay { get; set; }
    public string AirTime { get; set; }
    public string ContentRating { get; set; }
    public string ImdbId { get; set; }
    public int TvdbId { get; set; }
    public string Language { get; set; }
    public ImagesSerieVM Images { get; set; }
    public ICollection&lt;GenreVM&gt; Genres { get; set; }
    public DateTime Added { get; set; }
    public DateTime LastUpdated { get; set; }
    public string SlugName { get; set; }
}
</pre>
<p>In the full sample on <a href="https://github.com/qmatteoq/XamarinForms-Prism" target="_blank">GitHub</a> you’ll find many classes like this (which maps the various JSON responses returned by the TrackSeries APIs). Additionally, the <strong>TsApiService</strong> will implement additional methods, one for each API we want to leverage in our application. I won’t explain in details each method, since it would be out of scope for the article: you can see all the details on GitHub. For the purpose of this post, you just need to know that the service simply exposes a set of methods that we can use in the various ViewModels to retrieve info about the available TV Shows.</p>
<p><strong>Note:</strong> by default, the <strong>HttpClient</strong> class doesn’t offer a <strong>ReadAsAsync&lt;T&gt;</strong> method, which is able to automatically deserialize the JSON response into C# objects. To get access to this extension method, we need to add the <strong>Microsoft.AspNet.WebApi.Client</strong> NuGet package to our Portable Class Library. To get it properly working, you need to add this package to every project of the solution (the Xamarin Forms PCL, the Core PCL and all the platform specific projects).</p>
<p>To properly leverage <a href="http://blog.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">dependency injection</a>, however, we need an interface that describes the operations offered by the <strong>TsApiService</strong> class. Here is how our interface looks like:</p>
<pre class="brush: csharp;">public interface ITsApiService
{
    Task&lt;List&lt;SerieFollowersVM&gt;&gt; GetStatsTopSeries();
    Task&lt;SerieVM&gt; GetSerieByIdAll(int id);
    Task&lt;SerieInfoVM&gt; GetSerieById(int id);
    Task&lt;List&lt;SerieSearch&gt;&gt; GetSeriesSearch(string name);
    Task&lt;SerieFollowersVM&gt; GetStatsSerieHighlighted();
}
</pre>
<p>Now that we have a service, we can learn how, thanks to Prism, we can register it into its dependency container and have it automatically injected in our ViewModels. Actually, from this point of view, there’s nothing special to highlight: the approach is the same we would use with any other MVVM framework which leverages a dependency injection approach. First, we need to register the association between the interface and the implementation we want to use in the container. In case of Prism, we need to do it in the <strong>RegisterTypes()</strong> method of the <strong>App</strong> class, by using the <strong>Container</strong> object and the <strong>RegisterType&lt;T, Y</strong>&gt;<strong>()</strong> method (where <strong>T </strong>is the interface and <strong>Y</strong> is the concrete implementation):</p>
<pre class="brush: csharp;">protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation&lt;MainPage&gt;();
    Container.RegisterType&lt;ITsApiService, TsApiService&gt;();
}
</pre>
<p>Now, since both the <strong>MainPage</strong> and the <strong>TsApiService</strong> are registered in the container, we can get access to it in our ViewModel, by simply adding a parameter in the public constructor, like in the following sample:</p>
<pre class="brush: csharp;">public class MainPageViewModel : BindableBase
{
    private readonly ITsApiService _apiService;

    public MainPageViewModel(ITsApiService apiService)
    {
        _apiService = apiService;
    }
}
</pre>
<p>When the <strong>MainPageViewModel</strong> class will be loaded, the implementation of the <strong>ITsApiService</strong> we’ve registered in the container (in our case, the <strong>TsApiService</strong> class) will be automatically injected into the parameter in the constructor, allowing us to use it in all the other methods and properties we’re going to create in the ViewModel. With this approach, it will be easy for us to change the implementation of the service in case we need it: it will be enough to change the registered type in the <strong>App </strong>class and, automatically, every ViewModel will start to use the new version.</p>
<h3>Handle the navigation’s lifecycle</h3>
<p>Now that we have a service that offers a method to retrieve the list of the top series, we need to call it when the ViewModel is loaded: our goal is to display, in the main page of the app, a list of the most trending TV shows. However, we are about to face a common problem when it comes to use the MVVM pattern: the method to retrieve the list of top series is asynchronous but, with the current implementation, the only place where we can perform the data loading is the ViewModel’s constructor, which can’t execute asynchronous calls (in C#, in fact, the constructor of a class can’t be marked with the <strong>async </strong>keyword and, consequently, you can’t use the await prefix with a method). In a non-MVVM application, this problem would be easy to solve, thanks to the navigation’s lifecycle methods offered basically by every platform. Xamarin Forms makes no exception and we could leverage, in the code behind class of a XAML page, the methods <strong>OnAppearing()</strong> and <strong>OnDisappearing()</strong>: since they are events, we can call asynchronous code without issues.</p>
<p>To solve this problem, Prism offers an interface that we can implement in our ViewModels called <strong>INavigationAware</strong>: when we implement it, we have access to the <strong>OnNavigatedTo()</strong> and <strong>OnNavigatedFrom()</strong> events, which we can use to perform data loading or cleanup operations. Here is our <strong>MainPageViewModel</strong> looks like after implementing this interface:</p>
<pre class="brush: csharp;">public class MainPageViewModel : BindableBase, INavigationAware
{
    private readonly TsApiService _apiService;
    private ObservableCollection&lt;SerieFollowersVM&gt; _topSeries;

    public ObservableCollection&lt;SerieFollowersVM&gt; TopSeries
    {
        get { return _topSeries; }
        set { SetProperty(ref _topSeries, value); }
    }

    public MainPageViewModel(TsApiService apiService)
    {
        _apiService = apiService;
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public async void OnNavigatedTo(NavigationParameters parameters)
    {
        var result = await _apiService.GetStatsTopSeries();
        TopSeries = new ObservableCollection&lt;SerieFollowersVM&gt;(result);
    }
}
</pre>
<p>As you can see, now we have implemented a method called <strong>OnNavigatedTo()</strong>, where we can safely execute our asynchronous calls and load the data: we call the <strong>GetStatsTopSeries()</strong> method of the <strong>TsApiService </strong>class and we encapsulate the resulting collection into an <strong>ObservableCollection</strong> property. This is the property we’re going to connect, through binding, to a <strong>ListView</strong> control, in order to display the list of TV Shows in the main page.</p>
<p>For completeness, here is how the XAML of the <strong>MainPage</strong> looks like:</p>
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="InfoSeries.Views.MainPage"
             Title="Info Series"&gt;
  
  &lt;ContentPage.Resources&gt;
    &lt;ResourceDictionary&gt;
      &lt;DataTemplate x:Key="TopSeriesTemplate"&gt;
        &lt;ViewCell&gt;
          &lt;ViewCell.View&gt;
            &lt;Grid&gt;
              &lt;Grid.ColumnDefinitions&gt;
                &lt;ColumnDefinition Width="1*" /&gt;
                &lt;ColumnDefinition Width="2*" /&gt;
              &lt;/Grid.ColumnDefinitions&gt;

              &lt;Image Source="{Binding Images.Poster}" Grid.Column="0" x:Name="TopImage" /&gt;
              &lt;StackLayout Grid.Column="1" Margin="12, 0, 0, 0" VerticalOptions="Start"&gt;
                &lt;Label Text="{Binding Name}" FontSize="18" TextColor="#58666e" FontAttributes="Bold" /&gt;
                &lt;StackLayout Orientation="Horizontal"&gt;
                  &lt;Label Text="Runtime: " FontSize="14" TextColor="#58666e" /&gt;
                  &lt;Label Text="{Binding Runtime}" FontSize="14" TextColor="#98a6ad" Margin="5, 0, 0, 0" /&gt;
                &lt;/StackLayout&gt;
                &lt;StackLayout Orientation="Horizontal"&gt;
                  &lt;Label Text="Air day: " FontSize="14" TextColor="#58666e" /&gt;
                  &lt;Label Text="{Binding AirDay}" FontSize="14" TextColor="#98a6ad" Margin="5, 0, 0, 0" /&gt;
                &lt;/StackLayout&gt;
                &lt;StackLayout Orientation="Horizontal"&gt;
                  &lt;Label Text="Country: " FontSize="14" TextColor="#58666e" /&gt;
                  &lt;Label Text="{Binding Country}" FontSize="14" TextColor="#98a6ad" Margin="5, 0, 0, 0" /&gt;
                &lt;/StackLayout&gt;
                &lt;StackLayout Orientation="Horizontal"&gt;
                  &lt;Label Text="Network: " FontSize="14" TextColor="#58666e" /&gt;
                  &lt;Label Text="{Binding Network}" FontSize="14" TextColor="#98a6ad" Margin="5, 0, 0, 0" /&gt;
                &lt;/StackLayout&gt;
              &lt;/StackLayout&gt;
            &lt;/Grid&gt;
          &lt;/ViewCell.View&gt;
        &lt;/ViewCell&gt;


      &lt;/DataTemplate&gt;
    &lt;/ResourceDictionary&gt;
  &lt;/ContentPage.Resources&gt;

  &lt;ListView ItemTemplate="{StaticResource TopSeriesTemplate}"
            ItemsSource="{Binding Path=TopSeries}" RowHeight="200"/&gt;
  
&lt;/ContentPage&gt;
</pre>
<p>If you already know Xamarin Forms (or XAML in general), you should find this code easy to understand: the page contains a <strong>ListView</strong> control, with a template that describes how a single TV show looks like. We display the show’s poster, along with some other info like the title, the runtime, the production country, etc. Since, due to the naming convention, the <strong>MainPageViewModel</strong> class is already set as <strong>BindingContext</strong> of the page, we can simply connect them by binding the <strong>ItemsSource</strong> property of the <strong>ListView</strong> with the <strong>TopSeries</strong> collection we’ve previously populated in the ViewModel.</p>
<h3>Navigation with parameters</h3>
<p>We’ve seen how to leverage the <strong>OnNavigatedTo()</strong> method to perform data loading, but often this method is useful also for another scenario: retrieving parameters passed by a previous page, which are usually needed to understand the current context (in our sample, in the detail page of our application we need to understand which TV Show the user has selected).</p>
<p>Prism support this feature thanks to a class called <strong>NavigationParameters</strong>, which can be passed as optional parameter of the <strong>NavigationAsync()</strong> method of the <strong>NavigationService</strong> and it’s automatically included as parameter of the <strong>OnNavigatedTo()</strong> and <strong>OnNavigatedFrom()</strong> events. Let’s see how to leverage this feature, by adding a detail page to our application, where to display some additional info about the selected show.</p>
<p>The first step is to add both a new page in the <strong>Views </strong>folder (called <strong>DetailPage.xaml</strong>) and a new class in the <strong>ViewModels</strong> folder (called <strong>DetailPageViewModel.cs</strong>). You need to remember also that every page needs to be registered in the container in the <strong>App </strong>class, inside the <strong>OnRegisterTypes()</strong> method:</p>
<pre class="brush: csharp;">protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation&lt;MainPage&gt;();
    Container.RegisterTypeForNavigation&lt;DetailPage&gt;();
    Container.RegisterType&lt;ITsApiService, TsApiService&gt;();
}
</pre>
<p>Due to the naming convention, we don’t have to do anything special: the new page and the new ViewModel are already connected. Now we need to pass the selected item in the <strong>ListView</strong> control to the new page. Let’s see, first, how to handle the selection in the <strong>MainPage. </strong>We’ll get some help by a library created by my dear friend <a href="http://codeworks.it/blog/" target="_blank">Corrado Cavalli</a>, which allows to implement behaviors in a Xamarin Forms app. Among the available behaviors, one of them is called <strong>EventToCommand</strong> and it allows us to connect any event exposed by a control to a command defined in the ViewModel. We’re going to use it to connect the <strong>ItemTapped</strong> event of the <strong>ListView</strong> control (which is triggered when the user taps on an item in the list) to a command we’re going to create in the <strong>MainPageViewModel</strong> to trigger the navigation to the detail page.</p>
<p>You can install the package created by Corrado from NuGet: its name is <strong>Corcav.Behaviors</strong>. To use it, you need to add an additional namespace to the root of the <strong>MainPage</strong>, like in the following sample:</p>
<pre class="brush: xml;">&lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             xmlns:behaviors="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="InfoSeries.Views.MainPage"
             Title="Info Series"&gt;

    ...

&lt;/ContentPage&gt;
</pre>
<p>Then you can apply the behavior to the <strong>ListView</strong> control like you would do in a regular Windows app:</p>
<pre class="brush: xml;">&lt;ListView ItemTemplate="{StaticResource TopSeriesTemplate}"
          ItemsSource="{Binding Path=TopSeries}" RowHeight="200"&gt;
  &lt;behaviors:Interaction.Behaviors&gt;
    &lt;behaviors:BehaviorCollection&gt;
      &lt;behaviors:EventToCommand EventName="ItemTapped" Command="{Binding GoToDetailPage}" /&gt;
    &lt;/behaviors:BehaviorCollection&gt;
  &lt;/behaviors:Interaction.Behaviors&gt;
&lt;/ListView&gt;
</pre>
<p>Thanks to this behavior, we have connected the <strong>ItemTapped</strong> event of the <strong>ListView</strong> control to a command called <strong>GoToDetailPage</strong>, that we’re going to define in the ViewModel. From a framework point of view, Prism doesn’t do anything out of the ordinary to help developers implementing commands: it simply offers a class called <strong>DelegateCommand</strong>, which allows to define the operation to execute when the command is invoked and, optionally, the condition to satisfy to enable the command. If you have some previous experience with MVVM Light, it works exactly in the same way as the <strong>RelayCommand</strong> class. Here is how our command in the <strong>MainPageViewModel</strong> class looks like:</p>
<pre class="brush: csharp;">private DelegateCommand&lt;ItemTappedEventArgs&gt; _goToDetailPage;

public DelegateCommand&lt;ItemTappedEventArgs&gt; GoToDetailPage
{
    get
    {
        if (_goToDetailPage == null)
        {
            _goToDetailPage = new DelegateCommand&lt;ItemTappedEventArgs&gt;(async selected =&gt;
            {
                NavigationParameters param = new NavigationParameters();
                param.Add("show", selected.Item);
                await _navigationService.NavigateAsync("DetailPage", param);
            });
        }

        return _goToDetailPage;
    }
}
</pre>
<p>The command we have created is a parametrized command; in fact, the property type is <strong>DelegateCommand&lt;ItemTappedEventArgs&gt;: </strong>this way, inside the method, we get access to the selected item, which is stored in the <strong>Item</strong> property. The method invoked when the command is triggered shows you how navigation with parameter works: first we create a new <strong>NavigationParameters</strong> object which, in the end, is nothing but a dictionary, where you can store key / value pairs. Consequently, we simply add a new item with, as key, the keyword <strong>show</strong> and, as value, the selected item, which type is <strong>SerieFollowersVM. </strong>This is the only difference compared to the navigation we’ve seen in the <strong>App </strong>class: the rest is the same, which means that we call the <strong>NavigateAsync()</strong> method of the <strong>NavigationService</strong>, passing as parameter the key that identifies the detail page (which is <strong>DetailPage</strong>) and the parameter.</p>
<p><strong>Important!</strong> In the <strong>App</strong> class we were able to automatically use the <strong>NavigationService</strong> because it inherits from the <strong>PrismApplication </strong>class. If we want to use the <strong>NavigationService</strong> in a ViewModel (like in this case), we need to use the traditional approach based on dependency injection. The <strong>NavigationService</strong> instance is already registered in the Prism container, so we simply have to add an <strong>INavigationService</strong> parameter to the public constructor of the <strong>MainPageViewModel</strong>:</p>
<pre class="brush: csharp;">public MainPageViewModel(TsApiService apiService, INavigationService navigationService)
{
    _apiService = apiService;
    _navigationService = navigationService;
}
</pre>
<p>Now that we have performed the navigation to the detail page, we need to retrieve the parameter in the <strong>DetailPageViewModel </strong>class. The first step, like we did for the <strong>MainPageViewModel</strong>, is to let it inherit from the <strong>INavigationAware</strong> interface, other than the <strong>BindableBase </strong>class. This way, we have access to the <strong>OnNavigatedTo()</strong> event:</p>
<pre class="brush: csharp;">public class DetailPageViewModel : BindableBase, INavigationAware
{
    private SerieFollowersVM _selectedShow;

    public SerieFollowersVM SelectedShow
    {
        get { return _selectedShow; }
        set { SetProperty(ref _selectedShow, value); }
    }

    public DetailPageViewModel()
    {

    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {
            
    }

    public void OnNavigatedTo(NavigationParameters parameters)
    {
        SelectedShow = parameters["show"] as SerieFollowersVM;
    }
}
</pre>
<p>The previous code shows you how to handle the parameter we’ve received from the main page: the same <strong>NavigationParamaters</strong> object we’ve passed, in the <strong>MainPageViewModel</strong>, to the <strong>NavigateAsync()</strong> method is now passed as parameter of the <strong>OnNavigatedTo() </strong>method. As such, we can simply retrieve the item we’ve previously stored with the <strong>show</strong> key. In this case, since we are expecting an object which type is <strong>SerieFollowersVM</strong>, we can perform a cast and store it into a property of the ViewModel called <strong>SelectedShow.</strong> Thanks to this property, we can leverage binding to connect the various information of the selected show to the controls in the XAML page. Here is how the <strong>DetailPage.xaml</strong> looks like:</p>
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             Title="{Binding Path=SelectedShow.Name}"
             x:Class="InfoSeries.Views.DetailPage"&gt;

  &lt;StackLayout&gt;
    &lt;Image x:Name="InfoPoster"
           Source="{Binding Path=SelectedShow.Images.Fanart}" Aspect="AspectFill" /&gt;
    &lt;Label Text="{Binding Path=SelectedShow.Overview}" LineBreakMode="WordWrap" FontSize="13" TextColor="#98a6ad" Margin="15" /&gt;
  &lt;/StackLayout&gt;

&lt;/ContentPage&gt;
</pre>
<p>The content is very simple: we display an image of the show (stored in the <strong>SelectedShow.Images.Fanart</strong> property) and a brief description (stored in the <strong>SelectedShow.Overview</strong> property).</p>
<h3>Wrapping up</h3>
<p>In this post we’ve seen some basic concepts to handle navigation and dependency injection in a Xamarin Forms app created with Prism as MVVM framework. In the next post we’re going to see a couple of advanced scenarios, related to navigation and handling of platform specific code. You can find the sample app used for this post on my GitHub repository: <a title="https://github.com/qmatteoq/XamarinForms-Prism" href="https://github.com/qmatteoq/XamarinForms-Prism">https://github.com/qmatteoq/XamarinForms-Prism</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/prism-for-xamarin-forms-basic-navigation-and-dependency-injection-part-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Prism for Xamarin Forms &#8211; An overview (Part 1)</title>
		<link>https://www.qmatteoq.com/prism-for-xamarin-forms-an-overview-part-1/</link>
					<comments>https://www.qmatteoq.com/prism-for-xamarin-forms-an-overview-part-1/#comments</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 22 Aug 2016 14:00:00 +0000</pubDate>
				<category><![CDATA[Xamarin]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Xamarin Forms]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=6582</guid>

					<description><![CDATA[Even if I understand that it may not be the right technology for every project, I’m a huge fan of Xamarin Forms. As you’ll probably know if you follow my blog, I’m a Windows Developer and Xamarin Forms allows me &#8230; <a href="https://www.qmatteoq.com/prism-for-xamarin-forms-an-overview-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Even if I understand that it may not be the right technology for every project, I’m a huge fan of Xamarin Forms. As you’ll probably know if you follow my blog, I’m a Windows Developer and Xamarin Forms allows me to use basically all my current skills (XAML, binding, MVVM, etc.) to create applications also for other popular mobile platforms like iOS and Android. Additionally, it gives me the chance (like with native Xamarin) to take advantage of platform specific features and, at the same time, to maintain a user experience which is coherent with the look &amp; feel of the operating system. </p>
<p>I’ve recently used Xamarin Forms to create a porting for Android of my simple <a href="https://www.microsoft.com/store/apps/9wzdncrcsbsh" target="_blank">Qwertee Shirts app</a> and the advantage was clear: I was able to reuse most of the backend code I’ve already wrote for the UWP version and my XAML knowledge but, at the end, I got an application that fully embraced, from a UI point of view, the new Material Design created by Google, so it doesn’t look “alien” like it often happens with cross platform applications based on other cross platform technologies.</p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-12-10-58.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-20-12-10-58" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-20-12-10-58" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-12-10-58_thumb.png" width="254" height="452"></a></td>
<td valign="top" width="200"><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-12-11-19.png"><img loading="lazy" decoding="async" title="Screenshot_2016-08-20-12-11-19" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot_2016-08-20-12-11-19" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/Screenshot_2016-08-20-12-11-19_thumb.png" width="254" height="452"></a></td>
</tr>
</tbody>
</table>
<p>However, I’m not only a Windows Developer, but also a MVVM enthusiast and I’ve blogged about this topic multiple times, covering multiple platforms and frameworks. If you’re new to the MVVM pattern, I suggest you to start <a href="http://blog.qmatteoq.com/the-mvvm-pattern-introduction/" target="_blank">from this post</a> and move on with the rest of the series. As such, the first thing I did when I decided to resume working with Xamarin Forms to port my app was looking for the best way to reuse my MVVM knowledge to develop the project and, as usual, the choice was hard. In this case, it was even more complicated because Xamarin Forms, compared to other XAML technologies like WPF or UWP, is pretty new, so it was hard to find in the beginning a choice that completely satisfied me.</p>
<p>Don’t get me wrong, if you remember my posts about learning the MVVM pattern, you’ll know that I’m a huge fan of the flexibility offered by <a href="http://www.mvvmlight.net" target="_blank">MVVM Light</a> and Laurent Bugnion did a superb job to introduce typical MVVM concepts (like binding and commands) in platforms that don’t natively support them, like Android and iOS. However, Xamarin Forms is a bit different than standard Xamarin: it already offers the concepts we need to leverage the MVVM pattern, like binding, data context, dependency properties, behaviors, etc. In this scenario, MVVM Light is still a great choice but, however, you still have to reinvent the wheel to solve many common scenarios you have to deal with when you’re developing a XAML app, like handling navigation, getting access to navigation events in a ViewModel or passing parameters between one page to the other.</p>
<p>Even do it on purpose, right before starting my porting I saw <a href="http://brianlagunas.com/prism-for-xamarin-forms-6-2-release/" target="_blank">a tweet by Brian Lagunas</a>, one of the MVPs behind the Prism project, announcing a new version of Prism specific for Xamarin Forms. Just to refresh your mind, <a href="https://github.com/PrismLibrary/Prism" target="_blank">Prism</a> is a MVVM framework that, originally, was created by the Patterns &amp; Practices division by Microsoft and that, some times ago, has been turned into an open source project driven by the community. Prism has always been a great choice to implement the MVVM pattern in XAML based applications, but sometimes you may have faced the risk to make the project over complicated just to follow its naming conventions and rules (like the requirement of having a bootstrapper to initialize it, despite the fact that XAML based application already have a startup class called <strong>App</strong>).</p>
<p>After completing the porting, I’ve found myself very satisfied with the Prism approach for Xamarin Forms, so I’ve decided to share my experience with you, hoping that it will get you up &amp; running quicker when you start working on a new Xamarin Forms project.</p>
<h3></h3>
<h3>Creating the first project</h3>
<p>The easiest way to create a Xamarin Forms project based on Prism is to use its own Visual Studio extension, that you can download from the <a title="Visual Studio Gallery" href="https://visualstudiogallery.msdn.microsoft.com/e7b6bde2-ba59-43dd-9d14-58409940ffa0">Visual Studio Gallery</a>. After you’ve installed it, you will find in Visual Studio a new section called <strong>Prism</strong>, with various templates for each supported technology. The template we’re interested into is called <strong>Prism Unity App (Forms)</strong>:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism1.png"><img loading="lazy" decoding="async" title="prism1" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="prism1" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism1_thumb.png" width="601" height="416"></a></p>
<p>Actually, this template has even an advantage over the standard Xamarin Forms template. As you can see from the image below, it allows you to choose which platform you want to target when you create your project, while the default Xamarin Forms template automatically creates a project for each supported platforms (Android, iOS, Windows Phone 8.1, Windows 8.1, UWP), even if you aren’t interested in targeting one of them.</p>
<p><a href="http://3bo61w2s39sh2nxd9917cfju.wpengine.netdna-cdn.com/wp-content/uploads/2016/08/Project-Wizard.jpg"><img loading="lazy" decoding="async" title="Project Wizard" border="0" alt="Project Wizard" src="http://3bo61w2s39sh2nxd9917cfju.wpengine.netdna-cdn.com/wp-content/uploads/2016/08/Project-Wizard_thumb.jpg" width="338" height="396"></a></p>
<p>After you’ve hit the <strong>Create </strong>project, you will end up with a standard Xamarin Forms solution: one Portable Class Library and one specific project for each platform you’ve chosen. Additionally, the Portable Class Library will already contain:</p>
<ul>
<li>A <strong>Views</strong> folder, where to place your pages. The template includes a default one, called <strong>MainPage.xaml</strong>
<li>A <strong>ViewModels</strong> folder, where to place your ViewModels. The templates includes a default one, called <strong>MainPageViewModel.cs</strong>.
<li>An <strong>App </strong>class already configured to initialize the Prism infrastructure.</li>
</ul>
<p>Here is how your default project will look like:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism2.png"><img loading="lazy" decoding="async" title="prism2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="prism2" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism2_thumb.png" width="310" height="437"></a></p>
<p>To demo Prism for Xamarin Forms, I’m going to create a simple client for <a href="https://www.trackseries.tv/" target="_blank">TrackSeries</a>, a TV Show website created by my great friends and colleagues <a href="https://twitter.com/tracker086" target="_blank">Adrian Fernandez Garcia</a> and <a href="https://twitter.com/cj_aliaga" target="_blank">Carlos Jimenez Aliaga</a>.</p>
<p>Let’s start from the beginning and see which references have been automatically added by the template to the project:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism3.png"><img loading="lazy" decoding="async" title="prism3" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="prism3" src="http://blog.qmatteoq.com/wp-content/uploads/2016/08/prism3_thumb.png" width="479" height="349"></a></p>
<p>As you can see, other than the standard Xamarin Forms NuGet package, Prism requires two packages: a <strong>Core</strong> one (which is in common across every platform) and a <strong>Forms</strong> one (which, instead, contains the specific helpers and services for Xamarin Forms). By default, the standard template leverages Unity as dependency injection container, so you’ll find installed also a bunch of other packages like <strong>Unity</strong>, <strong>Prism.Unity.Forms</strong> and <strong>CommonServiceLocator</strong>. However, if you don’t like Unity, Prism for Xamarin Forms offers some additional packages to integrate other popular dependency injection containers, like <a href="https://www.nuget.org/packages/Prism.Ninject.Forms/" target="_blank">Ninject</a> or <a href="https://www.nuget.org/packages/Prism.Autofac.Forms/" target="_blank">Autofac</a>.</p>
<h3></h3>
<h3>The App class</h3>
<p>One of the biggest changes compared to the old Prism versions is the removal of the bootstrapper concept, which was a dedicated class of the project that took care of initializing all the Prism infrastructure. Xamarin Forms (as every other XAML technology) already has an initializer class: the <strong>App</strong> one, which is included in the Portable Class Library, so the team has decided to leverage it instead of asking to the developer to create a new one. By default, this class inherits from the <strong>Application </strong>class. To properly support Prism, we need to change this and let the <strong>App</strong> class inherit from the <strong>PrismApplication</strong> one by:</p>
<ul>
<li>In the <strong>App.xaml</strong> file, adding a new identifier for the namespace <strong>Prism.Unity</strong> and replacing the root <strong>Application </strong>node with the <strong>PrismApplication </strong>one.</li>
</ul>
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms"
                        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                        xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms"
                        x:Class="InfoSeries.App"&gt;

&lt;/prism:PrismApplication&gt;
</pre>
<ul>
<li>In the <strong>App.xaml.cs</strong> file<strong>, </strong>we need to change the default inheritance from <strong>Application</strong> to <strong>PrismApplication.</strong></li>
</ul>
<pre class="brush: csharp;">public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MainPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation&lt;MainPage&gt;();
    }
}</pre>
<p>Additionally, the <strong>App</strong> class has three distinctive features:</p>
<ul>
<li>It has a base constructor, which takes an <strong>IPlatformInitializer </strong>object as parameter.
<li>It has a method called <strong>OnInitialized()</strong>, where we initialize the Forms infrastructure (by calling the <strong>InitializeComponent()</strong> method) and we trigger the navigation to the main page of the app (we’ll see later in details how navigation works).
<li>It has a method called <strong>RegisterTypes()</strong>, which is where we register in the dependency injection container (in this case, Unity) every page and every service required by our application.</li>
</ul>
<p>The <strong>IPlatformInitializer </strong>parameter is <strong>null</strong> by default, but it can be leveraged in case you need to register in the dependency container some specific classes that exists only in a platform specific project. You will find, in fact, that every platform specific project has its own custom initializer class (<strong>AndroidInitializer </strong>for Android, <strong>UwpInitializer </strong>for UWP, etc.) which, however, by default has an empty implementation of the <strong>RegisterTypes()</strong> method. Here is, for example, how the <strong>MainPage.xaml.cs </strong>of the UWP project looks like:</p>
<pre class="brush: csharp;">public sealed partial class MainPage
{
    public MainPage()
    {
        this.InitializeComponent();

        LoadApplication(new DeepNavigation.App(new UwpInitializer()));
    }
}

public class UwpInitializer : IPlatformInitializer
{
    public void RegisterTypes(IUnityContainer container)
    {

    }
}
</pre>
<h3>Connecting Views and ViewModels</h3>
<p>As you should already know if you have some previous experience with MVVM , the key to make the pattern working is to connect the ViewModel with its own View through binding. The only difference in a Xamarin Forms app compared to a Windows app is that the property to define the context is called <strong>BindingContext</strong> and not <strong>DataContext</strong>. Prism makes use of a simple naming convention to automatically assign a ViewModel to its View:</p>
<ul>
<li>The XAML page should be stored into a folder of the project called <strong>Views </strong>
<li>The ViewModel should be stored into a folder of the project called <strong>ViewModels</strong> and it needs to have the same name of the page plus the suffix <strong>ViewModel </strong>(so, for example, the ViewModel connected to the <strong>MainPage.xaml</strong> will be called <strong>MainPageViewModel</strong>).</li>
</ul>
<p>As you can see, this is the exact infrastructure that the Prism template has created for us. Every page that we add to our application needs to be registered in the container, so that we can properly handle the navigation. To register it, we can leverage the <strong>RegisterTypes()</strong> method of the <strong>App</strong> class and use one of the methods offered by the <strong>Container</strong> called <strong>RegisterTypeForNavigation&lt;T&gt;</strong>, where <strong>T</strong> is the type of the page. In the starting template, we have just one page called <strong>MainPage,</strong> so it’s the only one that is automatically registered when the application starts. Here you can notice probably one of the biggest differences between Prism and other MVVM frameworks. With other toolkits, you are used to register in the container only the ViewModels and, eventually, all the services related to them. With Prism, instead, you just register the page’s type: it’s up to Prism to automatically register in the container also the ViewModel connected to the View. As you can see in the sample code, in fact, we have registered the <strong>MainPage</strong> class and not the <strong>MainPageViewModel</strong> one.</p>
<p>If you aren’t a fan of the naming convention approach, you aren’t forced to use it: in fact, the <strong>RegisterTypeForNavigation() </strong>method has another variant, which signature is <strong>RegisterTypeForNavigation&lt;T, Y&gt;()</strong>, where <strong>T</strong> is the page’s type and <strong>Y</strong> is the ViewModel’s type we want to set as <strong>BindingContext</strong>. So, for example, if you want to connect your <strong>MainPage</strong> to a ViewModel called <strong>MyCustomViewModel</strong>, it’s enough to register it using the following code:</p>
<pre class="brush: csharp;">protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation&lt;MainPage, MyCustomViewModel&gt;();
}
</pre>
<p>In the <strong>OnInitialized()</strong> method you can see a preview of how navigation works by default: every time you call the <strong>RegisterTypeForNavigation&lt;T&gt;</strong> method, Prism registers into the <strong>NavigationService</strong> a reference to that page using, as key, a string with the same type name. As such, since our page’s type is <strong>MainPage</strong>, we need to pass the string <strong>“MainPage”</strong> as parameter of the <strong>NavigateAsync()</strong> method to trigger the navigation to that page. If, by any chance, we want to override this behavior, we can pass as parameter of the <strong>RegisterTypeForNavigation&lt;T&gt;()</strong> a custom string and use it for the subsequent navigations, like in the following sample, where we have replaced the key <strong>“MainPage</strong>” with the <strong>“MyCustomPage” </strong>one.</p>
<pre class="brush: csharp;">public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MyCustomPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation&lt;MainPage&gt;("MyCustomPage");
    }
}
</pre>
<p>However, in the next posts we’ll see more details about how to handle navigation in a more advanced way.</p>
<h3>The ViewModel</h3>
<p>One of the features I’ve appreciated most of Prism for Xamarin Forms is that it doesn’t require us to do any change in XAML page to support it (for example, there are other MVVM frameworks which require you to change the <strong>ContentPage</strong> type with a custom one). You will only find, in the <strong>MainPage.xaml</strong> file, a specific Prism attribute, as property of the <strong>ContentPage</strong> entry, called <strong>ViewModelLocator.AutowireViewModel</strong>:</p>
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="InfoSeries.Views.MainPage"
             Title="MainPage"&gt;
  &lt;StackLayout HorizontalOptions="Center" VerticalOptions="Center"&gt;
    &lt;Label Text="{Binding Title}" /&gt;
  &lt;/StackLayout&gt;
&lt;/ContentPage&gt;
</pre>
<p>This property takes care of connecting the View with the ViewModel: when it’s set to <strong>true</strong>, the ViewModel will be automatically set as <strong>BindingContext</strong> of the View<strong> </strong>if we have respected the naming convention previously described. However, one of the changes introduced in Prism 6.2 is that this property isn’t required anymore, unless you want to explicitly disable the naming convention by setting it to <strong>false</strong>. The standard template adds it to give a more complete sample, but you can safely remove it.</p>
<p>A key feature offered by every MVVM framework is a class to use for our ViewModels to give quick access to the most used features, like the implementation of the <strong>INotifyPropertyChanged</strong> interface. Prism doesn’t make any exception and it offers a class called <strong>BindableBase</strong>, which our ViewModels can inherit from:</p>
<pre class="brush: csharp;">public class MainPageViewModel : BindableBase
{
    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public MainPageViewModel()
    {

    }
}
</pre>
<p>Thanks to this class, whenever we need to create a property that implements the <strong>INotifyPropertyChanged</strong> interface (so that it can propagate its changes through the binding channel), we can simply use the <strong>SetProperty()</strong> method in the setter of the property. This method will take care of storing the value and, at the same time, sending a notification to all the controls that are in binding with this property that its value has changed, so they need to update their layout.</p>
<p>The sample app created by template does exactly this: it creates a property called <strong>Title</strong>, which is connected through binding to a <strong>Label</strong> control in the XAML page. Whenever we change the value of the property, we will see the UI updated in real time. To be honest, the sample app shows also something different: it sets the value of the <strong>Title </strong>property in a method called <strong>OnNavigatedTo()</strong> and it parses some parameters. We’re going to see how this approach works more in details in the next post.</p>
<h3>In the next post</h3>
<p>In this post we have just scratched the surface and we understood the basic concept behind a Xamarin Forms application created with Prism. In the next post we’ll see some more advanced concepts, like handling navigation in a ViewModel or registering additional services in the dependency container.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/prism-for-xamarin-forms-an-overview-part-1/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Integrating Facebook in a Universal Windows app</title>
		<link>https://www.qmatteoq.com/integrating-facebook-in-a-universal-windows-app/</link>
					<comments>https://www.qmatteoq.com/integrating-facebook-in-a-universal-windows-app/#respond</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Fri, 12 Feb 2016 15:00:00 +0000</pubDate>
				<category><![CDATA[Universal Apps]]></category>
		<category><![CDATA[UWP]]></category>
		<category><![CDATA[wpdev]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Universal Windows Platform]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://blog.qmatteoq.com/?p=6560</guid>

					<description><![CDATA[Facebook is, without any doubt, one of the most popular social networks out there. There are many reasons why we would integrate their services into a mobile application: to make the login process easier, to allow sharing some content, to &#8230; <a href="https://www.qmatteoq.com/integrating-facebook-in-a-universal-windows-app/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Facebook is, without any doubt, one of the most popular social networks out there. There are many reasons why we would integrate their services into a mobile application: to make the login process easier, to allow sharing some content, to post something on the user’s timeline. <a href="http://blog.qmatteoq.com/integrating-facebook-in-your-windows-phone-app-using-the-facebook-app" target="_blank">I’ve already covered in the past on this blog</a> how to integrate Facebook in a Windows or Windows Phone application. In this post we’re going to see how to achieve this goal in a Universal Windows app for Windows 10 using a new Facebook SDK released <a href="https://github.com/microsoft/winsdkfb" target="_blank">by a Microsoft team on GitHub</a> a while ago. Specifically, we’re going to see how to retrieve the main information about the logged user and how to interact with the Graph APIs, the set of REST APIs provided by Facebook to access to their services.  </p>
<p>Let’s start!  </p>
<h1></h1>
<h1></h1>
<h3>Configuring the app</h3>
<p>The first step to start using the Facebook SDK is registering the app on the <a href="https://developers.facebook.com/" target="_blank">Facebook Developer Portal</a>: every mobile or web app which uses the Facebook APIs needs to be connected to an app registered on the Facebook portal. Without this step, Facebook won’t authorize us to perform any operation. Let’s point our browser to <a title="https://developers.facebook.com/" href="https://developers.facebook.com/">https://developers.facebook.com/</a> and choose to register a new app.</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/newapp.png"><img loading="lazy" decoding="async" title="newapp" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="newapp" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/newapp_thumb.png" width="471" height="257"></a></p>
<p>As you can see, the Windows platform isn’t listed by default, so you have to choose to perform a <strong>basic</strong> <strong>setup</strong> with the link at the bottom.</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook2.png"><img loading="lazy" decoding="async" title="facebook2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="facebook2" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook2_thumb.png" width="475" height="267"></a></p>
<p>The next step will ask you to set a display name (typically, it’s the same name of your application), an optional namespace (which acts as unique identifier for your app) and the category. In the end, press the <strong>Create App ID</strong> button. At the end of this step, your Facebook app will be created and ready to be configured. Now we need to add support to the Windows platform: we do it in the <strong>Settings</strong> section, which we can find in the menu on the left. In this page we’ll find the <strong>Add platform</strong> link, as highlighted in the below image:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook3.png"><img loading="lazy" decoding="async" title="facebook3" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="facebook3" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook3_thumb.png" width="466" height="223"></a></p>
<p>When you click on the link, this time, you’ll find an option called <strong>Windows App</strong> in the list. After you’ve chosen it, the following section will appear in the Settings page:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook4.png"><img loading="lazy" decoding="async" title="facebook4" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="facebook4" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/facebook4_thumb.png" width="502" height="134"></a></p>
<p>In our case, since it’s a Universal Windows app, we need to fill the <strong>Windows Store SID </strong>field<strong>; </strong>feel free to ignore the <strong>Windows Phone Store SID [BETA]</strong> field, since it applies only to old Silverlight apps for Windows Phone.</p>
<p>The SID is the unique identifier that the Windows Store assigns to our application when we associate it using the <strong>Store</strong> menu in Visual Studio. However, we don’t have to do it in advance to properly register the app on the Facebook portal. It’s enough to use the <strong>WebAuthenticationBroker</strong> class to retrieve this information: in case the app isn’t associated yet, we’ll retrieve a temporary value which is enough for our tests. Here is how to retrieve the SID in a Universal Windows app:</p>
<pre class="brush: csharp;">string sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); 
</pre>
<p>You have to take note of this value: the simplest approach is to use the <strong>Debug.WriteLine()</strong> method to print the value in the Visual Studio’s Output Window.</p>
<p>Here is how a SID looks like:</p>
<pre class="brush: plain;">ms-app://s-1-15-2-2031376880-2039615047-2889735989-2649504141-752107641-3656655002-2863893494/ 
</pre>
<p>This is the value we need to to put into the <strong>Windows Store SID</strong> field of the Facebook portal. However, we need to remove the <strong>ms-app://</strong> prefix and the ending <strong>/</strong>. So, based on the previous sample, the SID we would need to add in the developer’s portal is:</p>
<pre class="brush: plain;">s-1-15-2-2031376880-2039615047-2889735989-2649504141-752107641-3656655002-2863893494
</pre>
<p>The last thing to do is to take note of another information provided by Facebook: the <strong>App ID</strong>, which will need later during the login phase. You can find it in the main dashboard of your app, as you can see in the following image:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/clip_image002.png"><img loading="lazy" decoding="async" title="clip_image002" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image002" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/clip_image002_thumb.png" width="604" height="234"></a> </p>
<p>&nbsp;</p>
<p>Now we’ready to move on and write some code.</p>
<h3></h3>
<h3>Integrating the library</h3>
<p>The next step is to integrate the library into your app. Unfortunately, it isn’t available on NuGet, so you’ll need to download the whole project and compile it together with your app. The SDK is available on <a href="https://github.com/microsoft/winsdkfb" target="_blank">GitHub</a>, so there are two ways to get it:</p>
<ol>
<li>Using the <strong>Download ZIP</strong> button, to download a zipped file with the whole content of the repository.
<li>Cloning the repository on your computer using GIT.</li>
</ol>
<p>Personally, I suggest using the second approach: this way, you’ll be able to quickly get any update released by the team and keep your app always up-to-date. There are many ways to do it: you can choose the one you prefer, based on your experience with Git. The easiest one is to use the tools integrated in Visual Studio. Let’s see how:</p>
<ol>
<li>Open Visual Studio.
<li>Open the <strong>Team Explorer</strong> window. If it isn’t already available in your Visual Studio configuration, look for it in the <strong>View</strong> menu.
<li>You will find a section called <strong>Local Git repositories.</strong> Press the <strong>Clone </strong>button and set:
<ol>
<li>In the first field, the URL of the GitHub repository, which is <a title="https://github.com/microsoft/winsdkfb" href="https://github.com/microsoft/winsdkfb">https://github.com/microsoft/winsdkfb</a>
<li>In the second field, the local path on your computer where you want to save the project.</li>
</ol>
<li>Now press the <strong>Clone</strong> button: Visual Studio will download all the files in your local folder. Any time, by using Solution Explorer, you’ll be able to access to this repository and, by using the <strong>Sync</strong> button, to download the latest version of the source code from GitHub.</li>
</ol>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/git.png"><img loading="lazy" decoding="async" title="git" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="git" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/git_thumb.png" width="444" height="313"></a></p>
<p>Now that you have the library, you can add it to your Visual Studio solution that contains your Universal Windows app, right click on it, choose <strong>Add existing project </strong>and look for one of the projects of the Facebook SDK you’ve just cloned on your computer:</p>
<ol>
<li>If it’s a Universal Windows app for Windows 10 (so based on UWP), you need to add the project located at <em>FBWinSDK\FBSDK-UWP\FBSDK-UWP\FBSDK-UWP.vcxproj</em>
<li>If it’s a Windows Store app for Windows 8.1, you need to add the project located at <em>FBWinSDK\FBWinSDK\FBWinSDK.Windows\FBWinSDK.Windows.vcxproj</em>
<li>If it’s a Windows Store app for Windows Phone 8.1, you need to add the project located <em>FBWinSDK\FBWinSDK\FBWinSDK.WindowsPhone\FBWinSDK.WindowsPhone.</em>vcxproj </li>
</ol>
<p>The last step is to right click on your app’s project, choose <strong>Add reference</strong> and, from the <strong>Projects</strong> section, look for the Facebook project you’ve just added. Now you’re finally ready to write some code.</p>
<h3>The login phase</h3>
<p>The authentication to Facebook services is handled, as for many others similar services, using the oAuth protocol: the user will never share his credentials directly in the app, but inside a Web View which content is provided directly by the service’s owner (Facebook, in this case). If the credentials are accepted, Facebook wil return to the app a token, which we’ll need to perform any operation against the Facebook APIs. This approach improves the user’s security: a malicious developer won’t be able to access, in any case, to the user’s credentials.</p>
<p>The Facebook SDK we’ve added to our project makes easier to handle the login process: the Web View and the auhtentication will be handled directly by the library, which will return us automatically all the info about the logged user and a set of APIs to interact with the Graph APIs.</p>
<p>Here is the full login procedure:</p>
<pre class="brush: plain;">private async void OnLogin(object sender, RoutedEventArgs e)
{
    FBSession session = FBSession.ActiveSession;
    session.WinAppId = Sid;
    session.FBAppId = AppId;

    List&lt;string&gt; permissionList = new List&lt;string&gt;();
    permissionList.Add("public_profile");
    permissionList.Add("email");

    FBPermissions permissions = new FBPermissions(permissionList);
    var result = await session.LoginAsync(permissions);
    if (result.Succeeded)
    {
        //do something
    }
}

</pre>
<p>The first step is to retrieve the current session, by using the static property <strong>FBSession.ActiveSession</strong>. If we haven’t completed the login procedure yet, this property will be empty: in this case, we need to move on and continue the login procedure.</p>
<p>The first important properties to set are <strong>WinAppId </strong>and <strong>FBAppId</strong>. The first one is the SID of the application, the one we have previously retrieved using the <strong>GetCurrentApplicationCallbackUri()</strong> method of the <strong>WebAuthenticationBroker</strong> class. <strong>FBAppId</strong>, instead, is the App Id that we have noted before from the Facebook’s developer portal. The next step is to define which kind of operations we want to do with the Facebook APIs, by using the permissions mechanism. You can find the complete list of available permissions in the documentation <a href="https://developers.facebook.com/docs/facebook-login/permissions">https://developers.facebook.com/docs/facebook-login/permissions</a></p>
<p>It’s imortant to highlight how Facebook doesn’t allow to get access to all the permissions by default. Only the basic ones, like <strong>public_profile</strong> or <strong>email</strong>, are automatically allowed. The most advanced ones (like <strong>publish_actions</strong> that allows to publish a post on behalf of the user) require that the Facebook app passes a review process, where the team will double check the reasons and the use cases for which you’re requesting such permissions. Don’t confuse it with the certification process done by Microsoft when you submit the app on the Store: this review is completely handled by Facebook.</p>
<p>Permissions are defined into a collection of strings, which is passed as parameter when you initialize the <strong>FBPermissions</strong> object. The last step is to call the <strong>LoginAsync()</strong> method, passing as parameter the <strong>FBPermissions</strong> object you’ve just defined. When you call it, if the user has never logged in with your app, the SDK will display a popup, which will embed the Facebook login page, as you can see in the following image:</p>
<p><a href="http://blog.qmatteoq.com/wp-content/uploads/2016/02/clip_image004.jpg"><img loading="lazy" decoding="async" title="clip_image004" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="clip_image004" src="http://blog.qmatteoq.com/wp-content/uploads/2016/02/clip_image004_thumb.jpg" width="476" height="369"></a> </p>
<p>The user will have to fill his credentials and give to our app the authorization to access to the permissions we’ve required. If everything goes well, the method will return us a <strong>FBResult</strong> object with the outcome of the operation. The first property we can leverage is called <strong>Succeded</strong>, which will tell us if the login operation went well or not. In case the answer is yes, we can leverage the <strong>User</strong> property of the <strong>FBSession</strong> class to get access to all the public information of the user. The following code stores into a variable the full name of the user:</p>
<pre class="brush: csharp;">var result = await session.LoginAsync(permissions);
if (result.Succeeded)
{
    string name = session.User.Name;
}

</pre>
<h3>Interact with the Graph APIs</h3>
<p>As mentioned in the beginning of the post, Graph APIs are a set of REST APIs offered by Facebook that we can use to perform many operations, like publishing a post, liking a comment, etc. Let’s see how the SDK can help us to interact with these APIs with a real sample: retrieving the e-mail address of the user. It isn’t one of the information exposed by the public profile, so you won’t find an <strong>Email</strong> property in the <strong>FBUser</strong> class, but you’ll need to use the Graph APIs to get it.</p>
<p>As every REST API, an operation is defined by:</p>
<ol>
<li>An endpoint, which is the URL we need to invoke to interact with the service. In our scenario, we need to use the<strong> </strong><a href="https://graph.facebook.com/v2.5/me">https://graph.facebook.com/v2.5/me</a> endpoint, followed by the query string parameter <strong>fields </strong>with the list of information we need. In our case, the full endpoint will be <a href="https://graph.facebook.com/v2.5/me?fields=email">https://graph.facebook.com/v2.5/me?fields=email</a></li>
<li>A method exposed by the HTTP protocol, to be used in combination with the endpoint. Typically, when we’re retrieving some data we use the GET method; writing operations (like posting a status on Facebook), instead, are performed with the POST method. Our scenario falls in the first category, so we will perform a GET.</li>
</ol>
<p>The first thing we need is a class which maps the response that we’re going to receive from the API. For this purpose we can use the Graph API Explorer, a tool which we can use to simulate the operations with the Graph APIs and that is available at <a href="https://developers.facebook.com/tools/explorer">https://developers.facebook.com/tools/explorer</a> </p>
<p>The tool features an address bar, where we can specify the endpoint and the HTTP method we want to use. After pressing the <strong>Submit</strong> button, we’ll see in the main windows the JSON response returned by the API. If, for example, we perform a test with the endpoint we’re interested into (<strong>/me?fields=email</strong>) this is the response we’ll get:</p>
<pre class="brush: plain;">{
  "email": "mymail@mail.com",
  "id": "10203404048039813"
} 
</pre>
<p>Visual Studio offers a built-in option to convert a JSON data into a class. We just need to add a new class to the project and, once we have opened the file, using the option <strong>Paste Special –&gt; Paste JSON as classes</strong> which is available in the <strong>Edit</strong> menu. Visual Studio will generate the following class:</p>
<pre class="brush: csharp;">public class UserProfile
{
    public string id { get; set; }

    public string email { get; set; }
}

</pre>
<p>However, to properly use the Facebook SDK, we need also another element in the class: a static method which is able to deserialize the JSON returned by the service to convert it into a <strong>UserProfile</strong> object. We create it with the help of the popular JSON.NET library, which we need to install in the project using NuGet (<a href="https://www.nuget.org/packages/Newtonsoft.Json/">https://www.nuget.org/packages/Newtonsoft.Json/</a>).</p>
<p>This is the complete definition of the class:</p>
<pre class="brush: csharp;">public class UserProfile
{
    public string id { get; set; }

    public string email { get; set; }

    public static UserProfile FromJson(string jsonText)
    {
        UserProfile profile = JsonConvert.DeserializeObject&lt;UserProfile&gt;(jsonText);
        return profile;
    }
}

</pre>
<p>The <strong>FromJson()</strong> method uses the <strong>JsonConvert</strong> class to take as input the JSON returned by Facebook and to return, as output, a <strong>UserProfile</strong> object. To understand why we have created such a method, we need to analyze the code required to interact with the Graph APIs:</p>
<pre class="brush: csharp;">private async void OnGet(object sender, RoutedEventArgs e)
{
    string endpoint = "/me";

    PropertySet parameters = new PropertySet();
    parameters.Add("fields", "email");

    FBSingleValue value = new FBSingleValue(endpoint, parameters, UserProfile.FromJson);
    FBResult graphResult = await value.GetAsync();

    if (graphResult.Succeeded)
    {
        UserProfile profile = graphResult.Object as UserProfile;
        string email = profile?.email;
        MessageDialog dialog = new MessageDialog(email);
        await dialog.ShowAsync();
    }
}

</pre>
<p>The first step is to define the endpoint. It’s important to highlight that the query string parameters can’t be added directly in the URL, but separately using the <strong>PropertySet</strong> collection, otherwise we will get an exception at runtime. This happens because the SDK, under the hood, automatically sets the base URL for the APis and adds the access token retrieved during the login phase. You can notice it from the fact that we have just set the value <strong>/me</strong> as endpoint; we didn’t have to specify the full URL with the <a href="https://graph.facebook.com/v2.5/">https://graph.facebook.com/v2.5</a> prefix.</p>
<p>Using the <strong>PropertySet</strong> property is quite simple: it’s a collection, where we can add key-value pairs composed by a key (the name of the property, in our case <strong>fields</strong>) and a value (the property’s value, in our case <strong>email</strong>). In the next line of code you’ll finally understand why we had to create a <strong>FromJson()</strong> method inside the <strong>UserProfile</strong> class: it’s one of the paramters required when we initialize the <strong>FBSingleValue</strong> object, which is the class exposed by the SDK to interact with the Graph APIs. The other two parameters are the endpoind and the <strong>PropertySet</strong> collection with the list of parameters.</p>
<p>Now we are ready to perform the request. The <strong>FBSingleValue</strong> class offers many options, based on the HTTP method we need to use. In our case, since we need to perform a GET operation, we use the <strong>GetAsync()</strong> method, which will return us a <strong>FBResult</strong> object. It’s the same type of result we received during the login operation: this means that, also in this case, we can leverage the <strong>Succeded</strong> property to understand if the operation has completed succesfully or not. The difference is that, this time, we have also a <strong>Result</strong> property, which contains the result returned by the Graph API. It’s a generic <strong>object</strong>, since the Graph APIs don’t return a fixed structure; it’s our job to convert it into the type we expect, in this case a <strong>UserProfile</strong> object.</p>
<p>The rest is up to us and depends by our app’s logic: in the previous sample code, we just show to the user a dialog with the retrieved mail address.</p>
<p>This approach works for every interaction supported by the Graph APIs. What changes between one operation and the other is:</p>
<ol>
<li>The endpoint</li>
<li>The values to add to the <strong>PropertySet</strong> collection, based on the parameters required by the API.</li>
<li>The class to map the API’s response.</li>
<li>The method of the <strong>FBSingleValue</strong> class to call to perform the operation.</li>
</ol>
<p>For example, if instead of retrieving the user’s mail address we would have wanted to publish a post on the user’s timeline, we would have used the following code:</p>
<pre class="brush: csharp;">private async void OnPost(object sender, RoutedEventArgs e)
{
    PropertySet parameters = new PropertySet();
    parameters.Add("title", "Microsoft");
    parameters.Add("link", "https://www.microsoft.com/en-us/default.aspx");
    parameters.Add("description", "Microsoft home page");
    parameters.Add("message", "Posting from my Universal Windows app.");

    string path = "/me/feed";

    FBSingleValue sval = new FBSingleValue(path, parameters, FBReturnObject.FromJson);
    FBResult fbresult = await sval.PostAsync();

    if (fbresult.Succeeded)
    {
        // Posting succeeded
    }
    else
    {
        // Posting failed
    }
} 

</pre>
<p>The main difference here, other than the endpoint and the parameters, is that we’re dealing with a “write” operation. Consequently, we need to use the POST method of the HTTP protocol, which is translated into the <strong>PostAsync()</strong> method of the <strong>FBSingleValue</strong> class. As a reminder, remember that this method won’t work as it is: you’ll need to request the <strong>publish_actions</strong> permission, which is granted by Facebook only after the app has passed their review.</p>
<h3></h3>
<h3>Wrapping up</h3>
<p>In this post we’ve learned how to leverage the new Facebook SDK in a Universal Windows app to interact with the services offered by the popular social network. If you want to learn more, you can refer to the GitHub project (<a href="https://github.com/microsoft/winsdkfb">https://github.com/microsoft/winsdkfb</a>) and o the official documentation (<a href="http://microsoft.github.io/winsdkfb/">http://microsoft.github.io/winsdkfb/</a>). Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/integrating-facebook-in-a-universal-windows-app/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Scheduling toast notifications in a Universal Windows app</title>
		<link>https://www.qmatteoq.com/scheduling-toast-notifications-in-a-universal-windows-app/</link>
					<comments>https://www.qmatteoq.com/scheduling-toast-notifications-in-a-universal-windows-app/#comments</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 08 Feb 2016 15:00:00 +0000</pubDate>
				<category><![CDATA[Universal Apps]]></category>
		<category><![CDATA[UWP]]></category>
		<category><![CDATA[wpdev]]></category>
		<category><![CDATA[Universal Windows Platform]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://wp.qmatteoq.com/?p=6525</guid>

					<description><![CDATA[Toast notifications are, without any doubt, one of the most used techniques when it comes to notify something to the user, even when the app isn’t running. It’s almost impossible not to miss a toast notification: it plays a sound, &#8230; <a href="https://www.qmatteoq.com/scheduling-toast-notifications-in-a-universal-windows-app/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Toast notifications are, without any doubt, one of the most used techniques when it comes to notify something to the user, even when the app isn’t running. It’s almost impossible not to miss a toast notification: it plays a sound, it’s displayed on the screen, it’s stored in the Action Center and, on the phone, it makes also the device vibrate.</p>
<p>A toast notification is mapped with a XML file, which describes its content and its behavior. The flexibility in defining a toast notification has been vastly improved in Windows 10, since the Universal Windows Platform has added:</p>
<ol>
<li>More ways to customize the look &amp; feel of the notification. You can add images, multiple lines of text, etc.
<li>Support to interactive notifications. You can add interactive elements (like buttons or text boxes), which can be handled by a background task.</li>
</ol>
<p>You can learn more about the new features introduced in the Universal Windows Platform regarding toast notification in the following blog post from the team: <a title="http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10.aspx" href="http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10.aspx">http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10.aspx</a></p>
<p>In this post I would like to focus on the ways you can send a toast notification, specifically on scheduled toasts, since you may find some challenges in implementing them in the proper way.</p>
<h3>Sending toast notifications</h3>
<p>There are multiple ways to send a toast notification to the user:</p>
<ol>
<li><strong>Within the app:</strong> the Universal Windows Platform includes APIs like <strong>ToastNotification</strong> and <strong>ToastNotificationManager</strong> which can be used to send a toast notification when the app is running in foreground.
<li><strong>From a background task</strong>: the same APIs can be used also in a background task, so that toast notifications can be sent also when the app isn’t running.
<li><strong>Push notifications</strong>: a toast can be sent by a backend and received also when the app isn’t running. In this case, the app subscribes to a service offered by Microsoft (called WNS) and receives back a Url, which identifies the unique channel for that device. When the backend wants to send a push notification to that device, it executes a HTTP POST request to the Url including, in the body, the XML that describes the notification.
<li><strong>Scheduled notifications</strong>: by using the same APIs you use within the app you can create a toast notification and schedule it to be displayed at a specific time and date, even if the application isn’t running. This is the scenario we’re going to focus from now on.</li>
</ol>
<h3>Creating a scheduled toast notification</h3>
<p>Creating a scheduled toast notification is easy and you leverage the same APIs you would use for a standard toast notification sent by the app or by a background task. Here is a sample code:</p>
<pre class="brush: csharp;">private void OnScheduleToast(object sender, RoutedEventArgs e)
{
    string xml = @"&lt;toast&gt;
            &lt;visual&gt;
            &lt;binding template=""ToastGeneric""&gt;
                &lt;text&gt;Hello!&lt;/text&gt;
                &lt;text&gt;This is a scheduled toast!&lt;/text&gt;
            &lt;/binding&gt;
            &lt;/visual&gt;
        &lt;/toast&gt;";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    ScheduledToastNotification toast = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddSeconds(10));
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
}
</pre>
<p>The first step is to define the XML with the toast content. To learn how to define a toast, <a href="http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10.aspx" target="_blank">you can refer to the documentation</a> and you can get some help using <a href="https://www.microsoft.com/en-us/store/apps/notifications-visualizer/9nblggh5xsl1" target="_blank">Notifications Visualizer</a>, a Windows Store app by Microsoft that is able to give you an instant preview of how a specific XML will be rendered. </p>
<p><a href="http://wp.qmatteoq.com/wp-content/uploads/2016/02/snip_20160205175523.png"><img loading="lazy" decoding="async" title="snip_20160205175523" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="snip_20160205175523" src="http://wp.qmatteoq.com/wp-content/uploads/2016/02/snip_20160205175523_thumb.png" width="486" height="243"></a></p>
<p>Once you have the XML, you need to use it to create a <strong>XmlDocument</strong> object by calling the <strong>LoadXml()</strong> method and passing, as parameter, the XML string. Be aware that there are multiple classes called <strong>XmlDocument</strong> in the Universal Windows Platform: the one required by your scenario belongs to the <strong>Windows.Data.Xml.Dom</strong> namespace.</p>
<p>The last step is to create a new <strong>ScheduledToastNotification</strong> object, which is very similar to the basic <strong>ToastNotification</strong> one. The difference is that, this time, other than the <strong>XmlDocument</strong> object with the toast definition, you have to specificy also the date and time when the notification will be displayed, using a <strong>DateTimeOffset</strong> object. In the sample, we’re scheduling the notification to be display after 10 seconds that this code is executed. In the end, we schedule the notification by calling the <strong>AddToSchedule()</strong> method of the <strong>ToastNotifier </strong>object, which you can get by calling the <strong>CreateToastNotifier() </strong>method of the <strong>ToastNotificationManager</strong> class.</p>
<p>If you don’t like working with XML, you can use the Notifications Extensions library available on <a href="https://www.nuget.org/packages/NotificationsExtensions.Win10/" target="_blank">NuGet</a> and documented at <a title="http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/08/20/introducing-notificationsextensions-for-windows-10.aspx" href="http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/08/20/introducing-notificationsextensions-for-windows-10.aspx">http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/08/20/introducing-notificationsextensions-for-windows-10.aspx</a> This library gives you a set of classes and methods to create notifications and, under the hood, it takes care of generating the proper XML for you. For example, here is how the previous code looks like using the Notifications Extensions library:</p>
<pre class="brush: csharp;">private void OnScheduleToast(object sender, RoutedEventArgs e)
{
    ToastContent toastContent = new ToastContent
    {
        Visual = new ToastVisual
        {
            TitleText = new ToastText
            {
                Text = "Hello!"
            },
            BodyTextLine1 = new ToastText
            {
                Text = "This is a scheduled toast!"
            }
        }
    };

    XmlDocument doc = toastContent.GetXml();

    ScheduledToastNotification toast = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddSeconds(10));
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
}
</pre>
<h3>Scheduled notifications and locked devices</h3>
<p>If you try the previous code on a phone and, before the notification is displayed, you lock it by pressing the power button, you’ll realize that the notification won’t be displayed. As soon as you press the power button again to unlock the phone, you’ll see the notification appearing. What’s happening? The reason is that, by default, apps aren’t allowed to interact with the device when they’re locked, but they require a permission to do that. It’s a typical scenario when you work with background tasks: when you register a new task using the <strong>BackgroundTaskBuilder</strong> class you define a code similar to the following one:</p>
<pre class="brush: csharp;">protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    if (BackgroundTaskRegistration.AllTasks.All(x =&gt; x.Value.Name != "ToastTask"))
    {
        BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
        builder.Name = "ToastTask";
        builder.TaskEntryPoint = "ToastsTask.CheckAnswerTask";
        builder.SetTrigger(new ToastNotificationActionTrigger());
        var status = await BackgroundExecutionManager.RequestAccessAsync();
        if (status != BackgroundAccessStatus.Denied)
        {
            builder.Register();
        }
    }
    
}
</pre>
<p>You can notice that, after defining all the properties of the task (like the name, the entry point and the trigger we want to use) we call the <strong>RequestAccessAsync()</strong> method of the <strong>BackgroundExecutionManager</strong> class: only if the request isn’t denied, we move on to perform the real registration. The <strong>RequestAccessAsync()</strong> method makes sure that:</p>
<ol>
<li>We don’t have too many background tasks registered. On low memory devices, in fact, there’s a maximum number of tasks that can be registered and, if it has been reached, the OS will deny the request.</li>
<li>The background task is granted access to interact with the device also when it’s locked.</li>
</ol>
<p>As you can see, the second scenario is the one we need also for our scheduled toast notification: without this approval from the OS, we won’t be able to wake up the phone even if it’s locked. However, there’s a catch: the fact that we’re using scheduled toast notification doesn’t mean that we are necessarly using also a background task in our application. The problem is that, if we try to call the <strong>BackgroundExecutionManager.RequestAccessAsync()</strong> method without having a background task registered, we’ll get an exception.</p>
<p>The workaround is simple: register a fake background task. We don’t even need to add a Windows Runtime Component to our project: we just need to declare, in the manifest file, a fake background task. Open the manifest file of your app, go into the <strong>Declarations </strong>section and, from the dropdown menu, adds the <strong>Background task </strong>item. Then choose:</p>
<ol>
<li>As task type, <strong>System</strong>.</li>
<li>As entry point, any value (for example, <strong>Test</strong>). It doesn’t have to be a real entry point for a task, since we won’t try to register the task for real.</li>
</ol>
<p><a href="http://wp.qmatteoq.com/wp-content/uploads/2016/02/snip_20160205175826.png"><img loading="lazy" decoding="async" title="snip_20160205175826" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="snip_20160205175826" src="http://wp.qmatteoq.com/wp-content/uploads/2016/02/snip_20160205175826_thumb.png" width="359" height="308"></a></p>
<p>That’s all: the declaration in the manifet is enough for our scenario, since it will allow the <strong>BackgroundExecutionManager.RequestAccessAsync() </strong>method to be execute without any error. Now we just have to call this method when the app is starting, for example in the <strong>OnNavigatedTo()</strong> method of the page:</p>
<pre class="brush: csharp;">protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    await BackgroundExecutionManager.RequestAccessAsync();
}
</pre>
<p>That’s all. Now if you repeat the test of scheduling a notification and locking the phone before it’s displayed, you’ll correctly see the phone waking up and displaying the toast, like if it happens for regular push notifications.</p>
<p>Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/scheduling-toast-notifications-in-a-universal-windows-app/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>The MVVM pattern &#8211; Design time data</title>
		<link>https://www.qmatteoq.com/the-mvvm-pattern-design-time-data/</link>
					<comments>https://www.qmatteoq.com/the-mvvm-pattern-design-time-data/#respond</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 18 Jan 2016 15:00:00 +0000</pubDate>
				<category><![CDATA[Universal Apps]]></category>
		<category><![CDATA[UWP]]></category>
		<category><![CDATA[wpdev]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Universal Windows Platform]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://wp.qmatteoq.com/?p=6510</guid>

					<description><![CDATA[Ok, I’ve broken my promise. I’ve said that the previous post would have been the last one about MVVM, but I’ve changed my mind I realized, in fact, that I didn’t talk about one of the most interesting pros of &#8230; <a href="https://www.qmatteoq.com/the-mvvm-pattern-design-time-data/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Ok, I’ve broken my promise. I’ve said that <a href="http://wp.qmatteoq.com/?p=6495" target="_blank">the previous post</a> would have been the last one about MVVM, but I’ve changed my mind <img decoding="async" class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://wp.qmatteoq.com/wp-content/uploads/2016/01/wlEmoticon-smile.png" alt="Smile" /> I realized, in fact, that I didn’t talk about one of the most interesting pros of working with the MVVM pattern: design time data.</p>
<h3>Design time data</h3>
<p><a href="http://wp.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">In one of the posts of the series</a> we’ve talked about dependency injection, which is an easy way to swap the implementation of a service used by ViewModel. There are various reasons to do that: to make refactoring easier, to replace the data source in a quick way, etc. There’s another scenario for which dependency injection can be very useful: helping designers to define the user interface of the application. If this requirement is simple to satisfy when it comes to static data (like the header of a page), which are rendered in real time by the Visual Studio designer, things are a little bit more tricky with dynamic data. It’s very likely that most of the data displayed in the application isn’t static, but it’s loaded when the application is running: from a REST service, from a local database, etc. By default, all these scenarios don’t work when the XAML page is displayed in the designer, since the application isn’t effectively running. To solve this problem, the XAML has introduced the concept of <strong>design time data</strong>: it’s a way to define a data source that is displayed only when the XAML page is displayed in Visual Studio or in Blend in design mode, even if the app isn’t effectively running.</p>
<p>The MVVM pattern makes easier to support this scenario, thanks to the separation of layers provided by the pattern and the dependency injection approach: it’s enough to swap in the dependency container the service which provides the real data of the app with a fake one, which creates a set of static sample data.</p>
<p>However, compared <a href="http://wp.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">to the sample we’ve seen in the post about the dependency injection</a>, there are a couple of changes to do. Specifically, we need to detect when the XAML page is being displayed in the designer rather than at runtime and load the data from the correct data source. To do this, we use again one of the features offered by the MVVM Light toolkit, which is a property offered by the <strong>ViewModelBase</strong> class that tells us if a class is being used by the designer or by the running app.</p>
<p>Let’s see in details the changes we need to do. We’re going to use the same sample we’ve seen <a href="http://wp.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">in the post about dependency injection</a>, which can be found also on my GitHub repository <a title="https://github.com/qmatteoq/UWP-MVVMSamples" href="https://github.com/qmatteoq/UWP-MVVMSamples">https://github.com/qmatteoq/UWP-MVVMSamples</a>. The app is very simple: it displays a list of news, retrieved from a RSS feed. In the old post we implemented an interface, called <strong>IRssService</strong>, which offers a method with the following signature:</p>
<pre class="brush: csharp;">public interface IRssService
{
    Task&lt;List&lt;FeedItem&gt;&gt; GetNews(string url);
}
</pre>
<p>Then, the interface is implemented by two classes: one called <strong>RssService</strong>, which provides the real data from a real RSS feed, and one called <strong>FakeRssService</strong>, which provides instead fake static data.</p>
<pre class="brush: csharp;">public class RssService : IRssService
{
    public async Task&lt;List&lt;FeedItem&gt;&gt; GetNews(string url)
    {
        HttpClient client = new HttpClient();
        string result = await client.GetStringAsync(url);
        var xdoc = XDocument.Parse(result);
        return (from item in xdoc.Descendants(&quot;item&quot;)
                select new FeedItem
                {
                    Title = (string)item.Element(&quot;title&quot;),
                    Description = (string)item.Element(&quot;description&quot;),
                    Link = (string)item.Element(&quot;link&quot;),
                    PublishDate = DateTime.Parse((string)item.Element(&quot;pubDate&quot;))
                }).ToList();
    }
}

public class FakeRssService : IRssService
{
    public Task&lt;List&lt;FeedItem&gt;&gt; GetNews(string url)
    {
        List&lt;FeedItem&gt; items = new List&lt;FeedItem&gt;
        {
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 3),
                Title = &quot;Sample news 1&quot;
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 4),
                Title = &quot;Sample news 2&quot;
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 5),
                Title = &quot;Sample news 3&quot;
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 6),
                Title = &quot;Sample news 4&quot;
            }
        };

        return Task.FromResult(items);
    }
}
</pre>
<p>Before starting to explore the changes we need to do in the application to support design data, I would like to highlight a possible solution to handle asynchronous operations. One of the challenges in creating fake data comes from the fact that, typically, real services use asynchronous methods (since they retrieve data from a source which may take some time to be processed). The <strong>RssService</strong> is a good example: since the <strong>GetNews()</strong> method is asynchronous, it has to return a <strong>Task&lt;T&gt;</strong> object, so that it can be properly called by our ViewModel using the await keyword. However, it’s very unlikely that the fake service needs to use asynchronous methods: it just returns static data. The problem is that, since both services implement the same interface, we can’t have one service that returns <strong>Task</strong> operations while the other one plain objects. A workaround, as you can see from the sample code, is to use the <strong>FromResult()</strong> method of the <strong>Task</strong> class. Its purpose is to to encapsulate into a <strong>Task</strong> object a simple response. In this case, since the <strong>GetNews()</strong> method returns a <strong>Task&lt;List&lt;FeedItem&gt;&gt; </strong>response, we create a fake <strong>List&lt;FeedItem&gt;</strong> collection and we pass it to the <strong>Task.FromResult()</strong> method. This way, even if the method isn’t asynchronous, it will behave like if it is, so we can keep the same signature defined by the interface.</p>
<h3></h3>
<h3>The ViewModelLocator</h3>
<p>The first change we have to do is in the <strong>ViewModelLocator.</strong> In our sample app we have the following code, which registers into the dependency container the <strong>IRssService</strong> interface with the <strong>RssService</strong> implementation:</p>
<pre class="brush: csharp;">public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() =&gt; SimpleIoc.Default);

       
        SimpleIoc.Default.Register&lt;IRssService, RssService&gt;();
        SimpleIoc.Default.Register&lt;MainViewModel&gt;();
    }

    public MainViewModel Main =&gt; ServiceLocator.Current.GetInstance&lt;MainViewModel&gt;();
}</pre>
<p>We need to change the code so that, based on the way the app is being rendered, the proper service is used. We can ues the <strong>IsInDesignModeStatic</strong> property offered by the <strong>ViewModelBase</strong> class to detect if the app is running or if it’s being rendered by the designer:</p>
<pre class="brush: csharp;">public class ViewModelLocator
{

    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() =&gt; SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register&lt;IRssService, FakeRssService&gt;();
        }
        else
        {
            SimpleIoc.Default.Register&lt;IRssService, RssService&gt;();
        }

        SimpleIoc.Default.Register&lt;MainViewModel&gt;();
    }

    public MainViewModel Main =&gt; ServiceLocator.Current.GetInstance&lt;MainViewModel&gt;();
}</pre>
<p>In case the app is being rendered in the designer, we connect the <strong>IRssService</strong> interface with the <strong>FakeRssService</strong> class, which returns fake data. In case the app is running, instead, we connect the <strong>IRssService</strong> interface with the <strong>RssService</strong> class.</p>
<h3>The ViewModel</h3>
<p>To properly support design time data we need also to change a bit the ViewModel. The reason is that, when the app is rendered by the designer, isn’t really running; the designer takes care of initializing all the required classes (like the ViewModelLocator or the different ViewModels), but it doesn’t execute all the page events. As such, since typically the application loads the data leveraging events like <strong>OnNavigatedTo()</strong> or <strong>Loaded</strong>, we will never see them in the designer. Our sample app is a good example of this scenario: in our ViewModel we have a <strong>RelayCommand</strong> called <strong>LoadCommand</strong>, which takes care of retrieving the data from the <strong>RssService</strong>:</p>
<pre class="brush: csharp;">private RelayCommand _loadCommand;

public RelayCommand LoadCommand
{
    get
    {
        if (_loadCommand == null)
        {
            _loadCommand = new RelayCommand(async () =&gt;
            {
                List&lt;FeedItem&gt; items = await _rssService.GetNews(&quot;http://wp.qmatteoq.com/rss&quot;);
                News = new ObservableCollection&lt;FeedItem&gt;(items);
            });
        }

        return _loadCommand;
    }
}
</pre>
<p>By using the Behaviors SDK <a href="http://wp.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/" target="_blank">described in this post</a>, we have connected this command to the <strong>Loaded</strong> event of the page:</p>
<pre class="brush: xml;">&lt;Page
    x:Class=&quot;MVVMLight.Advanced.Views.MainView&quot;
    xmlns:interactivity=&quot;using:Microsoft.Xaml.Interactivity&quot;
    xmlns:core=&quot;using:Microsoft.Xaml.Interactions.Core&quot;
    DataContext=&quot;{Binding Source={StaticResource ViewModelLocator}, Path=Main}&quot;
    mc:Ignorable=&quot;d&quot;&gt;

    &lt;interactivity:Interaction.Behaviors&gt;
        &lt;core:EventTriggerBehavior EventName=&quot;Loaded&quot;&gt;
            &lt;core:InvokeCommandAction Command=&quot;{Binding Path=LoadCommand}&quot; /&gt;
        &lt;/core:EventTriggerBehavior&gt;
    &lt;/interactivity:Interaction.Behaviors&gt;

    &lt;!-- page content here --&gt;

&lt;/Page&gt;
</pre>
<p>However, when the page is being rendered in the designer, the <strong>LoadCommand</strong> command is never invoked, since the <strong>Loaded</strong> event of the page is never launched. As such, we have to retrieve the data from our service also in the ViewModel’s constructor which, instead, is executed by the designer when it creates an instance of our ViewModel. However, we need to do it only when the ViewModel is being rendered by the designer: when the app is running normally, it’s correct to leave the data loading operation to the command. To achieve this goal we leverage the <strong>IsInDesign</strong> property, which is part of the <strong>ViewModelBase</strong> class we’re already using as base class for our ViewModel:</p>
<pre class="brush: csharp;">public MainViewModel(IRssService rssService)
{
    _rssService = rssService;
    if (IsInDesignMode)
    {
        var task = _rssService.GetNews(&quot;abc&quot;);
        task.Wait();
        List&lt;FeedItem&gt; items = task.Result;
        News = new ObservableCollection&lt;FeedItem&gt;(items);
    }
}
</pre>
<p>Only if the app is running in design mode, we retrieve the data from the service and we populate the <strong>News</strong> property, which is the collection connected to the <strong>ListView</strong> control in the page. Since the <strong>GetNews()</strong> method is asynchronous and you can’t call asynchronous methods using the async / await pattern in the constructor, you need first to call the <strong>Wait()</strong> method on the <strong>Task</strong> and then access to the <strong>Result</strong> property to get the list of <strong>FeedItem</strong> objects. In a real application this approach would lead to a synchronous call, which would block the UI thread. However, since our <strong>FakeRssService</strong> isn’t really asynchronous, it won’t have any side effect.</p>
<p>This sample shows you also the reason why, in case you wanted to make things simpler, you can’t just call the <strong>GetNews()</strong> method in the constructor also when the application is running: since we’ can’t properly use the async / await pattern, we would end up with unpredictable behaviors. As such, it’s correct to continue calling the data loading methods in the page events that are triggered when the page is being loaded or navigated: since they’re simple methods or event handlers, they can be used with the async and await keywords.</p>
<h3>And we’re done!</h3>
<p>Now the job is done. If we launch the application, we should continue to normally see the data coming from the real RSS feed. However, if we open the <strong>MainPage.xaml</strong> page in the Visual Studio designer or in Blend, we should see something like this:</p>
<p><a href="http://wp.qmatteoq.com/wp-content/uploads/2016/01/snip_20160116230050.png"><img loading="lazy" decoding="async" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" title="snip_20160116230050" src="http://wp.qmatteoq.com/wp-content/uploads/2016/01/snip_20160116230050_thumb.png" alt="snip_20160116230050" width="696" height="522" border="0" /></a></p>
<p>The designer has created an instance of our ViewModel, which received from the dependency container a <strong>FakeRssService</strong> instance. Since the ViewModel is running in design mode, it will excecute the code we wrote in the constructor, which will retrieve the fake data. Nice, isn’t it? Thanks to this implementation, we can easily see how our collection of news will look like and, if it doesn’t satisfy us, easily change the <strong>DataTemplate</strong> we have defined in the <strong>ItemTemplate</strong> property.</p>
<p>As usual, you can find the sample code used in this blog post on my GitHub repository: <a title="https://github.com/qmatteoq/UWP-MVVMSamples" href="https://github.com/qmatteoq/UWP-MVVMSamples">https://github.com/qmatteoq/UWP-MVVMSamples</a> Specifically, you’ll find it in the project called <strong>MVVMLight.Advanced. </strong>Happy coding!</p>
<h2>Introduction to MVVM &#8211; The series</h2>
<ol>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-introduction/" target="_blank">Introduction</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-the-practice/" target="_blank">The practice</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">Dependency Injection</a></li>
<li><a href="http://blog.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/" target="_blank">Advanced scenarios</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/" target="_blank">Services, helpers and templates</a></li>
<li>Design time data</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/the-mvvm-pattern-design-time-data/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>The MVVM pattern &#8211; Services, helpers and templates</title>
		<link>https://www.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/</link>
					<comments>https://www.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/#respond</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Thu, 14 Jan 2016 15:00:00 +0000</pubDate>
				<category><![CDATA[Universal Apps]]></category>
		<category><![CDATA[UWP]]></category>
		<category><![CDATA[wpdev]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Universal Windows Platform]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://wp.qmatteoq.com/?p=6495</guid>

					<description><![CDATA[In this last post of the series about MVVM we’re going to introduce some concepts and libraries that can make your life easier when you develop a Universal Windows app leveraging the MVVM pattern. Services, services and services In one &#8230; <a href="https://www.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this last post of the series about MVVM we’re going to introduce some concepts and libraries that can make your life easier when you develop a Universal Windows app leveraging the MVVM pattern.</p>
<h3>Services, services and services</h3>
<p>In <a href="http://wp.qmatteoq.com/?p=6486" target="_blank">one of the previous posts</a> we have created a sample app to display a list of news retrieved from a RSS feed. While developing the app we introduced the concept of service: a class that takes care of performing some operations and passing the results to the ViewModel. Services can be useful also to reach another important goal of the MVVM pattern: avoiding writing platform specific code directly in the ViewModel, to make it easier to share them with other platforms or applications. As usual, I prefer to explain concepts with real examples, so let’s start with a new one.</p>
<p>Let’s say that you’re developing an awesome application that needs to display a dialog to the user. By applying the knowledge we’ve learned in the previous posts, you’ll probably end up to create a command like the following one:</p>
<pre class="brush: csharp;">private RelayCommand _showDialogCommand;

public RelayCommand ShowDialogCommand
{
    get
    {
        if (_showDialogCommand == null)
        {
            _showDialogCommand = new RelayCommand(async () =&gt;
            {
                MessageDialog dialog = new MessageDialog(&quot;Hello world&quot;);
                await dialog.ShowAsync();
            });
        }

        return _showDialogCommand;
    }
}
</pre>
<p>The command shows the dialog using a specific API of the Universal Windows Platform, which is the <strong>MessageDialog</strong> class. Now let’s say that your customer asks you to port this amazing app to another platform, like Android or iOS, using <a href="http://www.xamarin.com" target="_blank">Xamarin</a>, the cross-platform technology that allows to create apps for all the major mobile platforms using C# and the framework .NET. In this scenario, your ViewModel has a problem: you can’t reuse it as it is in Android or iOS, because they use a different API to display a message dialog. Moving platform specific code in a service is the best way to solve this problem: the goal is to change our ViewModel so that it just describes the operation to do (displaying a dialog) without actually implementing it.</p>
<p>Let’s start by creating an interface, which describes the operations to perform:</p>
<pre class="brush: csharp;">public interface IDialogService
{
    Task ShowDialogAsync(string message);
}
</pre>
<p>This interface will be implemented by a real class, which will be different for each platform. For example, the implementation for the Universal Windows Platform will be like the following one:</p>
<pre class="brush: csharp;">public class DialogService: IDialogService
{
    public async Task ShowDialogAsync(string message)
    {
        MessageDialog dialog = new MessageDialog(message);
        await dialog.ShowAsync();
    }
}
</pre>
<p>On Xamarin Android, instead, you will leverage the <strong>AlertDialog</strong> class, which is specific from Android:</p>
<pre class="brush: csharp;">public class DialogService : IDialogService
{
    public async Task ShowDialogAsync(string message)
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(Application.Context);

        alert.SetTitle(message);

        alert.SetPositiveButton(&quot;Ok&quot;, (senderAlert, args) =&gt;
        {

        });

        alert.SetNegativeButton(&quot;Cancel&quot;, (senderAlert, args) =&gt;
        {
        });
        alert.Show();

        await Task.Yield();
    }
}
</pre>
<p>Now that we have moved the platform specific APIs in a service, we can leverage the dependency injection approach (which <a href="http://wp.qmatteoq.com/?p=6486" target="_blank">I’ve described in a previous post</a>) to use, in the ViewModel, the interface instead of the real class. This way, our command will just describe the operation to perform, demanding to the <strong>DialogService</strong> class to effectively execute it. With this new approach, the ViewModel will add a dependency to the <strong>IDialogService</strong> class in the constructor, like in the following sample:</p>
<pre class="brush: csharp;">public class MainViewModel : ViewModelBase
{
    private readonly IDialogService _dialogService;

    public MainViewModel(IDialogService dialogService)
    {
        _dialogService = dialogService;
    }
}
</pre>
<p>Then we can change our command in the following way:</p>
<pre class="brush: csharp;">private RelayCommand _showDialogCommand;

public RelayCommand ShowDialogCommand
{
    get
    {
        if (_showDialogCommand == null)
        {
            _showDialogCommand = new RelayCommand(async () =&gt;
            {
                await _dialogService.ShowDialogAsync(&quot;Hello world&quot;);
            });
        }

        return _showDialogCommand;
    }
}
</pre>
<p>&nbsp;</p>
<p>By using the dependency injection approach, the Android application will register in the container the <strong>DialogService</strong> implementation which uses the Android APIs; vice versa, the Windows 10 application will register, instead, the implementation which uses the UWP APIs. However,now our ViewModel can be shared as it is between the two versions of the application, without having to change it. We can move the ViewModel, for example, in a Portable Class Library, which we can share across the Windows, Xamarin Android, Xamarin iOS, WPF, etc. versions of the application.</p>
<p>To help developers in moving the platform specific code into services, there are many libraries which offer a set of services ready to be used in your applications. One of the best ones, which plays well with MVVM Light, is Cimbalino Toolkit (<a title="http://cimbalino.org/" href="http://cimbalino.org/">http://cimbalino.org/</a>), which is specific for the Windows world. Other than many converters, behaviors and helpers classes, it includes a wide set of services to handle storage, settings, network access, etc. All the services are provided with their own interfaces, so that it’s easy to use them with the dependency inection’s approach.</p>
<p>If you want to know more about reusing your ViewModels on different platforms, I strongly suggest you to read <a href="https://msdn.microsoft.com/en-us/magazine/mt147239.aspx" target="_blank">this article</a> from Laurent Bugnion, the creator of MVVM Light itself. The tutorial will help you to learn how you can reuse your binding knowledge also on platforms like Android and iOS, which doesn’t support binding out of the box.</p>
<h3>Implementing the INotifyPropertyChanged interface in an easy way</h3>
<p>In the <a href="http://wp.qmatteoq.com/the-mvvm-pattern-the-practice/" target="_blank">second post of the series</a> we’ve learned that, to properly support the <strong>INotifyPropertyChanged </strong>interface, we need to change the way we define the properties in the ViewModel. We can’t use the standard get / set syntax, but in the setter we need to call a method that dispatches the notification to the binding channel that the value has changed. This approach makes the code more “noisy”, since the simple definition of a property requires many lines of code.</p>
<p>Please welcome <strong>Fody</strong>, a library that is able to change the code you wrote at build time. <strong>Fody</strong> offers many addons and one of them is called<strong> Fody.PropertyChanged. </strong>Its purpose is to automatically turn every standard property into a property that, under the hood, implements the <strong>INotifyPropertyChanged</strong> interface. All you have to do is to decorate your class (like a ViewModel) with the <strong>[ImplementPropertyChanged]</strong> attribute.</p>
<p>For example, the following code:</p>
<pre class="brush: csharp;">[ImplementPropertyChanged]
public class MainViewModel : ViewModelBase
{
    public string Message { get; set; }
}
</pre>
<p>is converted, during the compilation, into this:</p>
<pre class="brush: csharp;">public class MainViewModel: ViewModelBase, INotifyPropertyChanged 
{
    private string _message;

    public string Message 
    {
        get { return _message; }
        set 
        {
            _message = value;
            OnPropertyChanged(&quot;Message)
        }
    }
}
</pre>
<p>This way, you can simplify the code you need to write in your ViewModel and make it less verbose. To use this special attribute, you have to:</p>
<ol>
<li>Install the package called <strong>Fody.PropertyChanged </strong>from NuGet (<a title="https://www.nuget.org/packages/PropertyChanged.Fody/" href="https://www.nuget.org/packages/PropertyChanged.Fody/">https://www.nuget.org/packages/PropertyChanged.Fody/</a>)</li>
<li>To properly work, Fody requires a special XML file in the root of the project, which describes which is the addon to apply at compile time. The name of the file is <strong>FodyWeavers.xml</strong> and the content shoudl look like this:</li>
</ol>
<pre class="brush: xml;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;Weavers&gt;
  &lt;PropertyChanged /&gt;
&lt;/Weavers&gt;
</pre>
<p>That’s all!</p>
<h3></h3>
<h3></h3>
<h3>MVVM and Template10</h3>
<p><a href="https://github.com/Windows-XAML/Template10" target="_blank">Template10</a> is a new template, specific for Universal Windows apps development, which has been created to make the developer’s life easier, by providing a cleaner and simpler way to handle the initialization of an app, new controls, MVVM helpers, etc. Template10 is a great starting point also for MVVM apps, since it offers a set of classes that will help you to solve some of the platform specific challenges that may arise during the development, like handling the navigation or the page’s lifecycle. I won’t dig into this topic in this post, since I’ve already talked about it <a href="http://wp.qmatteoq.com/template10-a-new-template-to-create-universal-windows-apps-mvvm/" target="_blank">in another post on this blog</a>. If you’re planning to create a Universal Windows app with the MVVM pattern, I strongly suggest you to give it a read and evaluate it.</p>
<h3>That’s all folks!</h3>
<p>We’ve reached the end of our learning path. I hope you found these series useful to understand the power of the MVVM pattern and that, after reading it, you will try to develop your next application using it. As usual, remember that you can find the samples used as a reference in these posts on GitHub: <a title="https://github.com/qmatteoq/UWP-MVVMSamples" href="https://github.com/qmatteoq/UWP-MVVMSamples">https://github.com/qmatteoq/UWP-MVVMSamples</a> Happy coding!</p>
<h2>Introduction to MVVM &#8211; The series</h2>
<ol>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-introduction/" target="_blank">Introduction</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-the-practice/" target="_blank">The practice</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">Dependency Injection</a></li>
<li><a href="http://blog.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/" target="_blank">Advanced scenarios</a></li>
<li>Services, helpers and templates</li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-design-time-data/" target="_blank">Design time data</a></li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>The MVVM pattern &#8211; Advanced scenarios</title>
		<link>https://www.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/</link>
					<comments>https://www.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/#comments</comments>
		
		<dc:creator><![CDATA[qmatteoq]]></dc:creator>
		<pubDate>Mon, 11 Jan 2016 14:00:00 +0000</pubDate>
				<category><![CDATA[Universal Apps]]></category>
		<category><![CDATA[UWP]]></category>
		<category><![CDATA[wpdev]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Universal Windows Platform]]></category>
		<category><![CDATA[Windows 10]]></category>
		<guid isPermaLink="false">http://wp.qmatteoq.com/?p=6493</guid>

					<description><![CDATA[Let’s continue our journey to learn the MVVM pattern and how to apply it to develop a Universal Windows app. In this post we’re going to explore some advanced scenarios which are frequent when you develop a real project: how &#8230; <a href="https://www.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Let’s continue our journey to learn the MVVM pattern and how to apply it to develop a Universal Windows app. In this post we’re going to explore some advanced scenarios which are frequent when you develop a real project: how to handle secondary events, how to exchange message and how to use the dispatcher.</p>
<h3>Handling additional events with commands</h3>
<p>In <a href="http://wp.qmatteoq.com/the-mvvm-pattern-the-practice/" target="_blank">the previous posts</a> we’ve learned how all the XAML controls that allow user interaction, like a button, offer a property called <strong>Command</strong>, which we can use to connect an event to a method without using an event handler. However, the <strong>Command</strong> property can be used to handle only the main interaction event exposed by the control. For example, if you’re working with a<strong> Button</strong> control, you can use a command to handle the <strong>Click </strong>event. However, there are many scenarios where you need to handle secondary events. For example, the <strong>ListView</strong> control exposes an event called <strong>SelectionChanged,</strong> which is triggered when the user selects an item from the list. Or the <strong>Page</strong> class exposes a <strong>Loaded</strong> event that is triggered when the page is loaded.</p>
<p>To handle these situations we can leverage the Behaviors SDK, which is a library from Microsoft (recently turned into <a href="https://github.com/Microsoft/XamlBehaviors" target="_blank">an open source project on GitHub</a>) that contains a set of behaviors ready to be used in your apps. Behaviors are one of the most interesting XAML features, since they allow to encapsulate some logic, which typically should be handled in code behind, in components that can be reused directly in XAML. Behaviors are widely used in MVVM apps, since they help to reduce the code we need to write in the code behind classes.</p>
<p>A behavior is based on:</p>
<ol>
<li>A <strong>Trigger</strong>, which is the action that will cause the behavior’s execution.</li>
<li>An <strong>Action</strong>, which is the action to perform when the behavior is executed.</li>
</ol>
<p>The Behaviors SDK includes a set of triggers and actions which are specific to handle our scenario: connecting secondary events to commands defined in the ViewModel.</p>
<p>Let’s see a real example. The first step is to add the Behaviors SDK to your project. If you’re working on a Windows / Windows Phone / WPF / Silverlight project, the SDK is included in Visual Studio and it’s available in the <strong>Extensions </strong>section of the <strong>Add reference</strong> menu. Otherwise, if you’re working on a Windows 10 app, there’s a new version of the SDK which is available as a NuGet package, like any other library,  and that can be updated independently from Visual Studio and the Windows 10 SDK. To install it, it’s enough to right click on your project, choose <strong>Manage NuGet Packages</strong> and install the pacakge identified by the id <strong>Microsoft.Xaml.Behaviors.Uwp.Managed</strong> if it’s a C# / VB.NET application or <strong>Microsoft.Xaml.Behaviors.Uwp.Native</strong> if it’s a C++ application.</p>
<p>The next step is to declare, in the XAML page, the namespaces of the SDK, which are required to use the behaviors: <strong>Microsoft.Xaml.Interactivity</strong> and <strong>Microsoft.Xaml.Interactions.Code</strong>, like in the following sample.</p>
<pre class="brush: xml;">&lt;Page
    x:Class=&quot;MVVMLight.Advanced.Views.MainView&quot;
    xmlns:interactivity=&quot;using:Microsoft.Xaml.Interactivity&quot;
    xmlns:core=&quot;using:Microsoft.Xaml.Interactions.Core&quot;
    mc:Ignorable=&quot;d&quot;&gt;

&lt;/Page&gt;

</pre>
<p>Thanks to these namespaces, you’ll be able to use the following classes:</p>
<ol>
<li><strong>EventTriggerBehavior</strong>, which is the behavior that we can use to connect a trigger to any event exposed by a control.</li>
<li><strong>InvokeCommandAction</strong>, which is the action that we can use to connect a command defined in the ViewModel with the event handled by the trigger.</li>
</ol>
<p>Here is how we apply them to handle the selection of an item in a list:</p>
<pre class="brush: xml;">&lt;ListView ItemsSource=&quot;{Binding Path=News}&quot; 
          SelectedItem=&quot;{Binding Path=SelectedFeedItem, Mode=TwoWay}&quot;&gt;
    &lt;interactivity:Interaction.Behaviors&gt;
        &lt;core:EventTriggerBehavior EventName=&quot;SelectionChanged&quot;&gt;
            &lt;core:InvokeCommandAction Command=&quot;{Binding Path=ItemSelectedCommand}&quot; /&gt;
        &lt;/core:EventTriggerBehavior&gt;
    &lt;/interactivity:Interaction.Behaviors&gt;
&lt;/ListView&gt;

</pre>
<p>The behavior is declared like if it’s a complex property of the control and, as such, it’s included between the beginning and ending tag of the control itself (in this case, between <strong>&lt;ListView&gt; </strong>and <strong>&lt;/ListView&gt;</strong>). The behavior’s declaration is included inside a collection called <strong>Interaction.Behaviors</strong>, which is part of the <strong>Microsoft.Xaml.Interactivity</strong> namespace. It’s a collection since you can apply more than one behavior to the same control. In this case, we’re adding the <strong>EventTriggerBehavior</strong> mentioned before which requires, by using the <strong>EventName</strong> property, the name of the control’s event we want to handle. In this case, we want to manage the selection of an item in the list, so we link this property to the event called <strong>SelectionChanged</strong>.</p>
<p>Now that the behavior is linked to the event, we can declare which action we want to perform when the event is triggered. We can do it by leveraging the <strong>InvokeCommandActionClass</strong>, which exposes a <strong>Command</strong> property that we can link, using binding, to an <strong>ICommand</strong> property in the ViewModel.</p>
<p>The task is now completed: when the user will select an item from the list, the command called <strong>ItemSelectedCommand</strong> will be invoked. From a ViewModel point of view, there aren’t any difference between a standard command and a command connected to a behavior, as you can see in the following sample:</p>
<pre class="brush: csharp;">private RelayCommand _itemSelectedCommand;

public RelayCommand ItemSelectedCommand
{
    get
    {
        if (_itemSelectedCommand == null)
        {
            _itemSelectedCommand = new RelayCommand(() =&gt;
            {
                Debug.WriteLine(SelectedFeedItem.Title);
            });
        }

        return _itemSelectedCommand;

    }
}

</pre>
<p>This command takes care of displaying, in the Ouput Windows of Visual Studio (using the <strong>Debug.WriteLine()</strong> method), the title of the selected item. <strong>SelectedFeedItem</strong> is another property of the ViewModel which is connected, using binding, to the <strong>SelectedItem </strong>property of the <strong>ListView</strong> control. This way, the property will always store a reference to the item selected by the user in the list.</p>
<h3></h3>
<h3></h3>
<h3></h3>
<h3></h3>
<h3>Messages</h3>
<p>Another common requirement when you develop a complex app is to find a way to handle the communication between two classes that don’t have anything in common, like two ViewModels or a ViewModel and a code-behind class. Let’s say that, after something happened in a ViewModel, you want to trigger an animation in the View: in this case, the code that will perform it will be stored in the code-behind class, since we’re still talking about code that is related to the user interface.</p>
<p>In these scenarios, the strength of the MVVM pattern (which is a clear separation between the layers) can also become a weakness: how can we handle the communication between the View and ViewModel since they don’t have anything in common, exept for the second being set as DataContext of the first? These situations can be solved by using messages, which are packages that a centralized class can dispatch to the various classes of the application. The most important strength of these packages is that they are completely disconnected: there’s no relationship between the sender and the receiver. By using this approach:</p>
<ol>
<li>The sender (a ViewModel or a View) sends a message, specifying which is its type.</li>
<li>The receiver (another ViewModel or View) subscribes itself to receive messages which belongs to a specific type.</li>
</ol>
<p>In the end, a sender is able to send a message without knowing in advance who is going to receive it. Viceversa, the receiver is able to receive messages without knowing the sender. Every MVVM toolkit and framework typically offers a way to handle messages. MVVM Light makes no exceptions; we’re going to use the <strong>Messenger</strong> class to implement the sample I’ve previously described: starting an animation defined in the code behind from a ViewModel.</p>
<h3></h3>
<h4>The message</h4>
<p>The first step is to create the message we want to send from one class to the other. A message is just a simple class: let’s create a folder called <strong>Messages</strong> (it’s an optional step, it’s just to keep the structure of the project clean) and let’s right click on it in Visual Studio and choose <strong>Add –&gt; New item –&gt; Class</strong>. Here is how our message looks like:</p>
<pre class="brush: csharp;">public class StartAnimationMessage
{

}

</pre>
<p>As you can see, it’s just a class. In our case it’s empty, since we juts need to trigger an action. It can also have one or more properties in case, other than triggering an action, you need also to send some data from one class to  the other.</p>
<h4></h4>
<h4>The sender</h4>
<p>Let’s see now how our ViewModel can send the message we’ve just defined. We can do it by using the <strong>Messenger </strong>class, included in the namespace <strong>GalaSoft.MvvmLight.Messaging.</strong> In our sample, we assume that the animation will be triggered when the user presses a button. Consequently, we use the <strong>Messenger</strong> class inside a command, like in the following sample:</p>
<pre class="brush: csharp;">private RelayCommand _startAnimationCommand;

public RelayCommand StartAnimationCommand
{
    get
    {   
        if (_startAnimationCommand == null)
        {
            _startAnimationCommand = new RelayCommand(() =&gt;
            {
                Messenger.Default.Send&lt;StartAnimationMessage&gt;(new StartAnimationMessage());
            });
        }

        return _startAnimationCommand;
    }
}

</pre>
<p>Sending a message is quite easy. We use the <strong>Default</strong> property of the <strong>Messenger</strong> class to get access to the static instance of the messenger. Why static? Because, to properly work, it needs to be the same instance for the entire application, otherwise it won’t be able to dispatch and receive messages coming from different classes. To send a message we use the <strong>Send&lt;T&gt;()</strong> method, where <strong>T</strong> is the type of message we want to send. As parameter, we need to pass a new instance of the class we have previously created to define a message: in our sample, it’s the <strong>StartAnimationMessage</strong> one.</p>
<p>Now the message has been sent and it’s ready to be received by another class.</p>
<h4>The receiver</h4>
<p>The first step, before talking about how to receive a message, is to define in the XAML page the animation we want to trigger when the button is pressed, by using the <strong>Storyboard</strong> class:</p>
<pre class="brush: xml;">&lt;Page
    x:Class=&quot;MVVMLight.Messages.Views.MainView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:local=&quot;using:MVVMLight.Messages.Views&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    DataContext=&quot;{Binding Source={StaticResource ViewModelLocator}, Path=Main}&quot;
    mc:Ignorable=&quot;d&quot;&gt;

    &lt;Page.Resources&gt;
        &lt;Storyboard x:Name=&quot;RectangleAnimation&quot;&gt;
            &lt;DoubleAnimation Storyboard.TargetName=&quot;RectangleTranslate&quot;
                             Storyboard.TargetProperty=&quot;X&quot;
                             From=&quot;0&quot;
                             To=&quot;200&quot; 
                             Duration=&quot;00:00:05&quot; /&gt;
        &lt;/Storyboard&gt;
    &lt;/Page.Resources&gt;

    &lt;Grid Background=&quot;{ThemeResource ApplicationPageBackgroundThemeBrush}&quot;&gt;
        &lt;Rectangle Width=&quot;100&quot; Height=&quot;100&quot; Fill=&quot;Blue&quot;&gt;
            &lt;Rectangle.RenderTransform&gt;
                &lt;TranslateTransform x:Name=&quot;RectangleTranslate&quot; /&gt;
            &lt;/Rectangle.RenderTransform&gt;
        &lt;/Rectangle&gt;
    &lt;/Grid&gt;

    &lt;Page.BottomAppBar&gt;
        &lt;CommandBar&gt;
            &lt;CommandBar.PrimaryCommands&gt;
                &lt;AppBarButton Label=&quot;Play&quot; Icon=&quot;Play&quot; Command=&quot;{Binding Path=StartAnimationCommand}&quot; /&gt;
            &lt;/CommandBar.PrimaryCommands&gt;
        &lt;/CommandBar&gt;
    &lt;/Page.BottomAppBar&gt;
&lt;/Page&gt;

</pre>
<p>We have included in the page a <strong>Rectangle</strong> control and we have applied a <strong>TranslateTransform</strong>. It’s one of the transformations included in the XAML, which we can use to move a control in the page simply by changing its coordinates on the X and Y axis. The animation we’re going to create will be applied to this transformation and it will change the control’s coordinates.</p>
<p>The animation is defined using a <strong>Storyboard</strong> as a resource of the page: its type is <strong>DoubleAnimation</strong>, since it will change a property (the X coordinate of the <strong>TranslateTransform</strong>) which is represented by a number. The animation will move the rectangle from the coordinate 0 (the <strong>From</strong> property) to the coordinate 200 (the <strong>To</strong> property) in 5 seconds (the <strong>Duration</strong> property). To start this animation, we need to write some code in the code behind: in fact, we have to call the <strong>Begin()</strong> method of the <strong>Storyboardy </strong>control and, since it’s a page resource, we can’t access it directly from our ViewModel.</p>
<p>And here comes our problem: the animation can be started only in code behind, but the event that triggers it is raised by a command in the ViewModel. Thanks to our message, we can easily solve it: it’s enough to register the code behind class as receiver of the <strong>StartAnimationMessage</strong> object we’ve sent from the ViewModel. To do it we use again the <strong>Messenger </strong>class and its <strong>Default</strong> instance:</p>
<pre class="brush: csharp;">public sealed partial class MainView : Page
{
    public MainView()
    {
        this.InitializeComponent();
        Messenger.Default.Register&lt;StartAnimationMessage&gt;(this, message =&gt;
        {
            RectangleAnimation.Begin();
        });
    }
}

</pre>
<p>In the constructor of the page we use, this time, the <strong>Register&lt;T&gt;() </strong>method to turn the code behind class into a receiver. Also in this case, as <strong>T</strong>, we specify the type of message we want to receive; every other message’s type will be ignored. Moreover, the method requires two parameters:</p>
<ol>
<li>The first one is a reference to the class that will handle the message. In most of the cases, it’s the same class where we’re writing the code, so we simply use the <strong>this</strong> keyword.</li>
<li>An <strong>Action</strong>, which defines the code to execute when the message is received. As you can see in the sample (defined with an anonymous method) we get also a reference to the message object, so we can easily access to its properties if we have defined one or more of them to store some data. However, this isn’t our case: we just call the <strong>Begin()</strong> method of our <strong>Storyboard</strong>.</li>
</ol>
<p>Our job is done: now if we launch the application and we press the button, the ViewModel will broadcast a <strong>StartAnimationMessage</strong> package. However, since only the code behind class of our main page subscribed to it, it will be the only one to receive it and to be able to handle it.</p>
<h4>Be careful!</h4>
<p>When you work with messages, it’s important to remember that you may have configured your application to keep some pages in cache. This means that if we have configured a ViewModel or a code behind class to receive one or more messages, they may be albe to receive them even if they’re not visible at the moment. This can lead to some concurrency problems: the message we have sent may be received by a different class than the one we expect.</p>
<p>For this reason, the <strong>Messenger</strong> class offers a method called <strong>Unsubscribe&lt;T&gt;() </strong>to stop receiving messages which type is <strong>T</strong>. Typically, when you need to intercept messages in a code behind class, you need to remember to call it in the <strong>OnNavigatedFrom()</strong> event, so that when the user leaves the page it will stop receiving messages.</p>
<pre class="brush: csharp;">protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    Messenger.Default.Unregister&lt;StartAnimationMessage&gt;(this);
}

</pre>
<p>For the same reason, it’s also better to move the <strong>Register&lt;T&gt;()</strong> method from the constructor to the <strong>OnNavigatedTo()</strong> method of the page, to make sure that when the user navigates again to the page it will be able to receive messages again.</p>
<h3></h3>
<h3></h3>
<h3></h3>
<h3>Working with threads</h3>
<p>The user interface of Universal Windows app is managed by a single thread, called <strong>UI Thread</strong>. It’s critical to keep this thread as free as possible; if we start to perform too many operations on it, the user interface will start to be unresponsive and slow to use. However, at some point, we may need to access to this thread; for example, because we need to display the result of an operation in a control placed in the page. For this reason, most of the Universal Windows Platform APIs are implemented using the async / await pattern, which makes sure that long running operations aren’t performed on the UI thread, leaving it empty to process the user interface and the user interactions. At the same time, the result is automatically returned on the UI thread, so it’s immediately ready to be used by any control in the page.</p>
<p>However, there are some scenario where this dispatching isn’t done automatically. Let’s take, as example, the <strong>Geolocator</strong> API, which is provided by the Universal Windows Platform to detect the location of the user. If you need to continuosly track the user’s position, the class offers an event called <strong>PositionChanged</strong>, which you can subscribe with an event handler to get all the information about the detected location (like the coordinates). Let’s build a sample app that starts tracking the user’s position and displays the coordinates in the page. The structure of the project is the same we’ve already used in all the other samples: we’ll have a View (with a Button and a TextBlock) connected to a ViewModel, with a command (to start the detection) and a string property (to display the coordinates).</p>
<p><strong>Please note: </strong>the purpose of the next sample is just to show you a scenario where handling the UI thread in the proper way is important. In a real project, using a platform specific API (in this case, the <strong>Geolocator</strong> one) in a ViewModel isn’t the best approach. We’ll learn more in the next post.</p>
<p>Here is how the ViewModel looks like:</p>
<pre class="brush: csharp;">public class MainViewModel: ViewModelBase
{
    private readonly Geolocator _geolocator;

    public MainViewModel()
    {
        _geolocator = new Geolocator();
        _geolocator.DesiredAccuracy = PositionAccuracy.High;
        _geolocator.MovementThreshold = 50;
    }

    private string _coordinates;

    public string Coordinates
    {
        get { return _coordinates; }
        set { Set(ref _coordinates, value); }
    }

    private RelayCommand _startGeolocationCommand;

    public RelayCommand StartGeolocationCommand
    {
        get
        {
            if (_startGeolocationCommand == null)
            {
                _startGeolocationCommand = new RelayCommand(() =&gt;
                {
                    _geolocator.PositionChanged += _geolocator_PositionChanged;
                });
            }

            return _startGeolocationCommand;
        }
    }

    private void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
    {
        Coordinates =
            $&quot;{args.Position.Coordinate.Point.Position.Latitude}, {args.Position.Coordinate.Point.Position.Longitude}&quot;;
    }
}
</pre>
<p>&nbsp;</p>
<p>When the ViewModel is created, we initialize the <strong>Geolocator</strong> class required to interact with the location services of the phone. Then, in the <strong>StartGeolocationCommand</strong>, we define an action that subscribes to the <strong>PositionChanged</strong> event of the <strong>Geolocator</strong>: from now on, the device will start detecting the location of the user and will trigger the event every time the position changes. In the event handler we set the <strong>Coordinates</strong> property with a string, which is the combination of the <strong>Latitude</strong> and <strong>Longitude</strong> properties returned by the handler.</p>
<p>The View is very simple: it’s just a <strong>Button</strong> (connected to the <strong>StartGeolocationCommand </strong>property) and a <strong>TextBlock</strong> (connected to the <strong>Message</strong> property).</p>
<pre class="brush: xml;">&lt;Page
    x:Class=&quot;MVVMLight.Dispatcher.Views.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:local=&quot;using:MVVMLight.Dispatcher&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    DataContext=&quot;{Binding Source={StaticResource Locator}, Path=Main}&quot;
    mc:Ignorable=&quot;d&quot;&gt;

    &lt;Grid Background=&quot;{ThemeResource ApplicationPageBackgroundThemeBrush}&quot;&gt;
        &lt;StackPanel HorizontalAlignment=&quot;Center&quot;
                    VerticalAlignment=&quot;Center&quot;&gt;
            &lt;Button Content=&quot;Start geolocalization&quot; Command=&quot;{Binding Path=StartGeolocationCommand}&quot; /&gt;
            &lt;TextBlock HorizontalAlignment=&quot;Center&quot;
                   VerticalAlignment=&quot;Center&quot;
                   Text=&quot;{Binding Path=Coordinates}&quot; /&gt;
        &lt;/StackPanel&gt;
    &lt;/Grid&gt;
&lt;/Page&gt;

</pre>
<p>If we try the application and we press the button, we will notice that, after a few seconds, Visual Studio will show an error like this:</p>
<p><a href="http://wp.qmatteoq.com/wp-content/uploads/2016/01/dispatcher.png"><img loading="lazy" decoding="async" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;" title="dispatcher" src="http://wp.qmatteoq.com/wp-content/uploads/2016/01/dispatcher_thumb.png" alt="dispatcher" width="1000" height="467" border="0" /></a></p>
<p>&nbsp;</p>
<p>The reason is that, to keep the UI thread free, the event handler called <strong>PositionChanged </strong>is executed on a different thread than the UI one, which doesn’t have direct access to the UI one. Since the <strong>Coordinates</strong> property is connected using binding to a control in the page, as soon as we try to change its value we’ll get the exception displayed in the picture.</p>
<p>For these scenarios the Universal Windows Platform provides a class called <strong>Dispatcher</strong>, which is able to dispatch an operation on the UI thread, no matter which is the thread where it’s being executed. The problem is that, typically, this class can be accessed only from code-behind, making harder to use it from a ViewModel. Consequently, most of the MVVM toolkits provide a way to access to dispatcher also from a ViewModel. In MVVM Light, this way is represented by the <strong>DispatcherHelper</strong> class, which requires to be initialized when the app starts in the <strong>OnLaunched()</strong> method of the <strong>App</strong> class:</p>
<pre class="brush: csharp;">protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page
        rootFrame = new Frame();

        rootFrame.NavigationFailed += OnNavigationFailed;
        DispatcherHelper.Initialize();

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }

        // Place the frame in the current Window
        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        // When the navigation stack isn&#039;t restored navigate to the first page,
        // configuring the new page by passing required information as a navigation
        // parameter
        rootFrame.Navigate(typeof(Views.MainPage), e.Arguments);
    }
    // Ensure the current window is active
    Window.Current.Activate();
}
</pre>
<p><strong>DispatcherHelper</strong> is a static class, so you can directly call the <strong>Initialize() </strong>method without having to create a new instance. Now that it’s initialized, you can start using it in your ViewModels:</p>
<pre class="brush: csharp;">private async void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
    await DispatcherHelper.RunAsync(() =&gt;
    {
        Coordinates =
            $&quot;{args.Position.Coordinate.Point.Position.Latitude}, {args.Position.Coordinate.Point.Position.Longitude}&quot;;
    });
}
</pre>
<p>The code that needs to be executed in the UI thread is wrapped inside an <strong>Action</strong>, which is passed as parameter of the asynchronous method <strong>RunAsync()</strong>. To keep the UI thread as free as possible, it’s important to wrap inside this action only the code that  actually needs to be executed on the UI thread and not other logic. For example, if we would have needed to perform some additional operations before setting the <strong>Coordinates</strong> property (like converting the coordinates in a civic address), we would have performed it outside the <strong>RunAsync()</strong> method.</p>
<h3>In the next post</h3>
<p>In the next and last post of the series we’re going to see some additional libraries and helpers that we can combine with MVVM Light to make our life easier when it comes to develop a Universal Windows app. In the meantime, as usual, you can play with the sample code used in this post that has been published on my GitHub repository at <a title="https://github.com/qmatteoq/UWP-MVVMSamples" href="https://github.com/qmatteoq/UWP-MVVMSamples">https://github.com/qmatteoq/UWP-MVVMSamples</a></p>
<h2>Introduction to MVVM &#8211; The series</h2>
<ol>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-introduction/" target="_blank">Introduction</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-the-practice/" target="_blank">The practice</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-dependency-injection/" target="_blank">Dependency Injection</a></li>
<li>Advanced scenarios</li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-services-helpers-and-templates/" target="_blank">Services, helpers and templates</a></li>
<li><a href="http://blog.qmatteoq.com/the-mvvm-pattern-design-time-data/" target="_blank">Design time data</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qmatteoq.com/introduction-to-mvvm-advanced-scenarios/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
