Tag Archives: MVVM Xamarin.Forms

Restructuring the Xamarin.Forms Shell Default App Template…

Let’s restructure the default project Template for Xamarin.Forms Shell Apps provided by Visual Studio 2019, clean it up, optimize it for the best use of Shell features. 😉

To be more detailed when you create a fresh Xamarin.Forms Shell app, in Visual Studio 2019, you get a certain default template app project provided by VS2019, let me show you how to restructure it in a clean and optimized manner for best use of features, performance and code structure.

Xamarin.Forms Shell is Awesome…

but I had quite a bit confusion understand the reason behind it and the bells and whistles of it, let me explain! So I’ve been working extensively with Xamarin framework for over 4 years now, and I’m confident to say that I have expertized myself on the best use of it. 😀

The way Xamarin.Forms Shell was marketed for was to provide a better alternative for dealing with Master Detailed or Tab Page based Xamarin.Forms Apps. This really made sense to me, since I knew how troublesome or the complexity we have to deal with in those scenarios.

Template Project mess?!

I went through the documentation, followed up on some demo code the community had shared, and once I was confident, it was time to get my hands dirty. So I created a fresh new Xamarin.Forms Shell project in Visual Studio 2019, and started going through the code.

It was a messy chaos! Since the first line of code, it was confusing, with many different Xamairn.Forms implementation practices all over the place in both UI and C# code behind, Xamarin.Forms Classic and Shell navigation mixed up in all over the project and so on. Took me quite a while to get a hold of it. 😦

This is quite a bad set up for a Template project, could be very disorienting for anyone who’s fresh starting off with Xamarin.Forms Shell, let alone Xamarin.Forms itself.

But why?

My best bet is that they wanted to give the perception to the developer that you can interchange and mix up as you like, Xamarin.Forms Classic bits and Shell bits. This is probably in a good intention, but for anyone who’s just starting to grasp it, could be very confusing, mixing up everything together in a template project.

Sure Xamarin.Forms Classic and Shell are completely interchangeable elements, but for a template, you need to give a clear, straight forward way to get started for anyone.

Ze Solution!

So my solution, is to adopt only Xamarin.Forms Shell related implementation, features, and practices into the default Template, so it gives a clear, easy to understand, straight forward view of using Xamairn.Forms Shell to build apps. Thinking in terms of simplest terms, decoupled components with clean and readable code, we need to reflect the best practices of Xamarin.Forms in the Template. 😉

So here I am sharing my journey of restructuring the default project Template for Xamarin.Forms Shell Apps step by step… Also I would like to share this as a guide to fixing up an existing messy project, with all the good coding practices in mind when it comes to Xamarin.Forms! 😀

Default Template Project…

Let’s take a proper look at the what you get fresh out of the box when you create a new Xamarin.Forms Shell project in VS2019 as of now,

So as you can see it promotes MVVM structure in the project, with Models, Views, and ViewModels separated, while also having a separate DataStore service. The basic functionality of this app is to Write text note items with a Title and Description and save them in the memory.

The app consists of ItemsPage where it shows all the text notes added, then ItemDetailsPage where you can view each of the notes, then the NewItemPage which is a modal page allowing you to add new text items, finally a simple AboutPage with a little intro to the Xamarin.Forms Shell.

Issues need Fixes…

Now let me walk you through some of the main problematic bits I found in this template project, one by one…

BindingContext init() inconsistent…

The BindingContext initialization with the ViewModel instance it all over the place, while some pages having it in code behind in the constructor.

And others having it in the XAML itself as shown below..

This should be unified either to code behind Constructor or the other only.

NewItemsPage, no ViewModel!?

For the NewItemsPage, there’s no ViewModel available, and it sets the BindingContext to itself as shown below…

This needs to be modified with its own ViewModel class, and move these data functions into it.

Missing Shell  Query Parameters…

The recommended way to pass data between pages in Xamarin.Forms Shell is to use Query Parameter strings, but this is not reflected in the Template project at all. As you can see below, it uses a tightly coupled Constructor parameter object passing instead.

This needs to be changed to use Xamarin.Forms Shell query parameters, as recommended.

Need to unify Color Resources…

Apart from the global Colors and Styles resources defined in the App.xaml, there are page level resources added as well in some pages.

This should be removed and switched to use global context Colors for better re-usability and reduce repetition of code.

Classic Xamarin.Forms Navigation!? Why!?

Now this was a serious WHY? moment I had when I first saw this, no where in the template project is using actual Xamarin.Forms Shell Route based navigation.

All over the project you will see the Classic Xamarin.Forms Navigation being used.

This needs to be changed to use the actual Shell Route based navigation.

To make it worse, for Modal pages, it implements a very bad practice of forcefully pushing the Navigation Bar on top of it. 😮

Now you can see why I have complained it’s a messy mix of everything, which needs cleaning up with a proper project structure.

Let the Restructuring begin!

Let me walk yol through the whole restructuring process I did step by step, so that you get a clear idea how to make changes in your own projects. Also have pushed this up in my Github repo, if you’re interested in taking a peek.

hosted on github:
github.com/UdaraAlwis/XFShellTemplateDemoApp

Alright then let’s on ahead…

Step 1: Cleaning up Colors and Styles…

Let’s get rid of the page level Color values and move them to the App.xaml, allowing them to be shared on an app global context, increasing re-usability and removing redundancy.

<!--
	Application Styles and Resources
-->
<Application.Resources>
	<ResourceDictionary>
		<Color x:Key="Primary">#2196F3</Color>
		<Color x:Key="Accent">#96d1ff</Color>
		<Color x:Key="LightTextColor">#999999</Color>
	</ResourceDictionary>
</Application.Resources>

Make sure to keep one key for each color value, and share that in all the required elements. Now we have a much cleaner XAML! 😉

Step 2: BaseViewModel to Infrastructure!

The BaseViewModel.cs class is not actively being instantiated but provides a base for the ViewModels of the project, so it would make sense to move out the BaseViewModel.cs class into a separate folder called, Infrastructure.

Also let’s do a bit of code refactoring inside the BaseViewModel, with the field naming, such as private fields, by adding _fieldName format as a good C# code standard.

Step 3: BindingContext in the Constructor()

Let’s have the ViewModel instantiation and its assigning to the Page.BindingContext, inside the Constructor() of each page. Yep, and don’t forget to remove the XAML set up added in the default template. 😉

public partial class ItemsPage : ContentPage
{
    private readonly ItemsViewModel _viewModel;

    public ItemsPage()
    {
        InitializeComponent();

        BindingContext = _viewModel = new ItemsViewModel();
    }
    
    ...
}

This would give better control over the ViewModel’s object instance. The private field will be named accordingly with the “_” prefix, and kept as a private readonly field, since its only going to be instantiated once in the Constructor itself. Make sure to propagate the same for all the Pages in the project.

Step 4: Clean up ItemDetailViewModel!

We need to clean up the ItemDetailViewModel, to be stand-alone and loosely coupled. This will also help us in implementing a proper Shell Route based navigation later.

Let’s convert the Item property into a full fledged property with a private backing field, GETter and SETter. 😉 In the constructor, get rid of the parameter passed in, and let’s assign a dummy value to it as default value.

public class ItemDetailViewModel : BaseViewModel
{
	private Item _item;

	public Item Item
	{
		get => _item;
		private set
		{
			SetProperty(ref _item, value);
			Title = _item?.Text;
		}
	}

	public Command LoadItemCommand { get; set; }

	public ItemDetailViewModel()
	{
		var item = new Item
		{       
                        Id = Guid.NewGuid().ToString(),
			Text = "Sample Item",
			Description = "This is an item description."
		};

		Item = item;

		LoadItemCommand = new Command<string>(async (itemId) => await LoadItem(itemId));
	}

	private async Task LoadItem(string itemId)
	{
		Item = await DataStore.GetItemAsync(itemId);
	}
}

Apart from the Item property, I have added a new Command, which will load the Item details object from the DataStore service.

Now that a well structured, clean ViewModel eh! Next let’s handle the parameter that we’re suppose to pass from ItemsPage to ItemDetailPage…

Step 5: Setting up Query Parameters…

As a part of the previous step, we need to handle the selected Item object that’s being passed into the ItemDetailPage. We’re going to handle this properly with Xamarin.Forms Shell Query parameters. So let’s pass the Id value of the selected Item object, as a query parameter into the page as follows, with the QueryProperty attribute.

[QueryProperty(nameof(ItemId), "itemid")]
public partial class ItemDetailPage : ContentPage
{
	private readonly ItemDetailViewModel _viewModel;
	private string _itemId;

	public string ItemId
	{
		get => _itemId;
		set => _itemId = Uri.UnescapeDataString(value);
	}
	
	...
}

Here we’re maintaining ItemId string property in the Page, where Shell we set the query value into during the navigation.

Do not forget to fire up the LoadItemCommand in the ViewModel of the page, with the ItemId that we acquired during navigation.

...
public partial class ItemDetailPage : ContentPage
{	
	...	
	protected override void OnAppearing()
	{
		base.OnAppearing();

		_viewModel.LoadItemCommand.Execute(ItemId);
	}
}

Alright, then let’s fix the navigation bits next…

Step 6: Use proper Shell Navigation!

Instead of using Xamarin.Forms Classic navigation, let’s migrate all the Navigation bits to proper Xamarin.Forms Shell Route based Navigation yeah!

Let’s start by registering the Page routes, that we use for navigation. Preferably using lower case letters for all the routes.

public partial class AppShell : Xamarin.Forms.Shell
{
	public AppShell()
	{
		InitializeComponent();

		Routing.RegisterRoute("itemdetailpage", typeof(ItemDetailPage));
		Routing.RegisterRoute("newitempage", typeof(NewItemPage));
	}
}

Then update all the navigation bits to use Shell route based navigation…

...
public partial class ItemsPage : ContentPage
{    
    ...
    private async void OnItemSelected(object sender, SelectedItemChangedEventArgs args)
    {
        ...

        await Shell.Current.
                    GoToAsync($"/itemdetailpage?itemid={item.Id.ToString()}");
        ...
    }
}

Now, that’s a proper Shell Navigation in action!

Step 7: Set up NewItemViewModel!

NewItemPage does not have a ViewModel created against it, in order to maintain a proper MVVM structure we need to move all the code behind bits in NewItemPage.xaml.cs into the NewItemViewModel as follows…

public class NewItemViewModel : BaseViewModel
{
    private Item _item;

    public Item Item
    {
        get => _item;
        set
        {
            SetProperty(ref _item, value);
        }
    }

    public NewItemViewModel()
    {
        var item = new Item
        {
           ...
        };

        Item = item;
    }
}

The in the page constructor we assign the instance of this ViewModel to the BindingContext, and you’re done..

Step 8: Use proper Modal Navigation!

The NewItemPage is treated as a Modal page, we should use Shell.PresentationMode instead of classic Navigation.PushModalAsync() for navigating to Modal pages.

First of all make sure we’re navigating to the NewItemPage properly using Shell Route navigation as follows,

...
public partial class ItemsPage : ContentPage
{    
    ...
    private async void AddItem_Clicked(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync($"/newitempage");
    }
}

Next we set up Shell.PresentationMode property in the NewItemPage to render the page navigation as the Modal page we expect it to be, using ModalAnimated value.

<ContentPage
    x:Class="XFShellTemplateDemoApp.Views.NewItemPage"
    xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    ios:Page.UseSafeArea="true"
    Shell.PresentationMode="ModalAnimated">

	<!--  Content of the Page  -->
	
	... 

</ContentPage>

Also we should set up the UseSafeArea property for iOS to ignore the iPhone notch, since Modal page overlays the whole app window.

Finally, let’s get rid of the NavigationBar based buttons and use Page Content based Buttons, and modify the UI layout accordingly.

<ContentPage
    x:Class="XFShellTemplateDemoApp.Views.NewItemPage"
    Shell.PresentationMode="ModalAnimated">

    <ContentPage.Content>
        <Grid Margin="0" Padding="0">

            ...

            <StackLayout Padding="15" Orientation="Horizontal">
                <Button
                    BackgroundColor="{StaticResource Primary}"
                    Clicked="Cancel_Clicked"
                    HorizontalOptions="FillAndExpand"
                    Text="Cancel"
                    TextColor="White" />
                <Button
                    BackgroundColor="{StaticResource Primary}"
                    Clicked="Save_Clicked"
                    HorizontalOptions="FillAndExpand"
                    Text="Save"
                    TextColor="White" />
            </StackLayout>

            ...

        </Grid>
    </ContentPage.Content>
</ContentPage>

I have created separate Cancel and Save Buttons which is inside a StackLayout, which in return is inside in the parent Grid Layout where rest of the content resides.

...
public partial class NewItemPage : ContentPage
{    
    ...
    private async void Cancel_Clicked(object sender, EventArgs e)
    {
        await Shell.Current.Navigation.PopModalAsync();
    }
}

For dismissing the page we can stick to PopModalAsync() call in the Navigation stack, since Shell doesn’t have it’s own for that.

Step 9: Overall code quality clean up…

Apart from all these structural changes, another aspect I heavily focused on was, the readability of the code and maintaining proper coding standards, down to the variable naming.

It’s important to properly write the code with all these little details in mind so that its easy to read and understandable by anyone who try to understand the code.

Alright then, with that I conclude the restructuring!

Restructured Template Project…

Aaand let’s take a proper look at what we got at the end after the extensive restructuring of the Xamarin.Forms Shell Template project in VS2019,

Here’s it in action in iOS!

in Android!

Once again you may find the whole project code is hosted on my Github repo,

hosted on github:
github.com/UdaraAlwis/XFShellTemplateDemoApp

Feel free to fork it out and use it as anyway you wish, may be even for a starter pack for your Xamarin.Forms Shell App development journey! 😉

Conclusion!

Well that concludes my journey of restructuring the Xamarin.Forms Shell default project template in VS2019, for the best use of Shell features, performance and optimized clean code.

Xamarin.Forms Shell is actually an awesome new paradigm to build Xamarin.Forms app, but honestly the VS2019 Template project could really use some proper restructuring for making it easier and straight forward for the beginners to start off. 😉

Share the love! 😀 Cheers yol!

Advanced Prism Tab Navigation with MVVM & Test friendly manner in Xamarin.Forms!

If you’re looking for how to navigate inside a Xamarin.Forms Tab Page programatically in a MVVM friendly and Test-able manner, without having any XAML-Code-Behind garbage. Welcome to my post!

Keep in mind, since this is an advanced topic, there’s not going to be any step by step intro’s to Prism or MVVM or whatnot ;)!

Sneak Peak!

Here’s a little sneak peak of the outcome of it.

PERKS:

  • Switch between Child-Tabs when you are,
    • Coming into the TabbedPage
    • Already in the TabbedPage
    • Coming back to the TabbedPage
  • Fully MVVM compatible
  • Fully Test-able, yaay!
  • Binding, Commands and Interfaces FTW!
  • Almost no XAML-code-behind garbage
  • Coming back to the TabbedPage, the Child-Tab switching occurs only when the TabbedPage is actually visible

How cool is that eh! 😉

 

Woot! Let’s get started then…

My MVVM addiction…

You know me, I’m all about that MVVM & Test-able Software Architecture life forever yol! xD

Being hustling with one of the best dot net application craftsman, has made a massive impact on my perspective of software engineering, rather than just writing some code, putting some shit together and make it work. I’m extremely obsessed with architecture of any given application I develop now, long last extendability, and fully test driven approach. High quality, clean code with all of dot net standards and complete separation of Views and ViewModels.

Backstory…

So recently, I was working on this Xamarin.Forms application which was using Prism as the MVVM framework with a fully test driven architecture. There we had all of our Views and ViewModels separately implemented with a clean architecture, whereas we didn’t have a single line of extra XAML-code-behind garbage. 😛

So the requirement was to implement a TabbedPage and which should be able to switch between its Child-Tabs programatically at runtime, to be more specific, we should be able switch the selected Child-Tab when the user is:

  • Coming into the TabbedPage
  • Already in the TabbedPage
  • Coming back to the TabbedPage after navigating forward.

And the most interesting part was this we had to handle this in a fully MVVM and Testable manner. 😮

Now this would have been much easier, if you had taken out the whole MVVM and Test-first aspect out of the equation, with some dirty XAML-code-behind garbage you can easily handle this. But in this situation, I was backed against the wall, How on earth could anyone achieve this?

but as usual, I figured it out!

The Recipe time…

So here’s how I implemented it, in conclusion we’re going to use an Interface that will allow us to bridge the View-ViewModel separation and a Bindable property inside the TabbedPage, that will react to the changes of the ViewModel’s “SelectedTab” property.

That interface is going to be implemented into the ViewModel. Then through the ViewModel we’re going to register that whole instance in our IoC container, when the user navigates into the TabbedPage. The bindable-property of the TabbedPage will be bound to the property in ViewModel. 😀

Which will allow us to access the interface instance from the IoC container from anywhere in our code and change the Selected Child-Tab.

Oh also I forgot to mention that with Prism, by default we can set the selected Tab-Child when we ‘first navigate into the Tab Page’, so handling that scenario is going to be a no-brainer, thus I will not focus on it in this post.

We shall work on navigating inside the TabbedPage when we’re already inside it, and when we’re coming back to the TabbedPage from another page after navigating forward. Which is going to be a piece of cake with our interface implementation approach.

Just to add something extra, we will maintain a flag property inside the TabbedPage, to make sure to allow the Selected Child-Tab switching happens only when the TabbedPage is visible to the user. Just to make it look nicer!

Since all of this is a simple combination of Bindable-Properties, Interfaces and Commands, this whole implementation is fully test-able. Yeah fine, I’ll show you how to write some tests for it as well! 😛

Sounds pretty straight forward eh! 😀 time for coding! 😉

Implementation time…

So just a heads up, my project configuration is as follows.

I’m using a Xamarin.Forms project (dot net Standard 2.0) created with Prism Templates for Visual Studio. And the IoC container is the default Unity container comes with Prism.Forms setup. As of the Tests I’m using a xUnit Dot net project, which I will get into details later.

So before you begin make sure you have the above setting in place.

1. interface to save the day…

First, the simple Interface which is going to save the day like we discussed above…

public interface IMyTabbedPageSelectedTab
{
	int SelectedTab { get; set; }

	void SetSelectedTab(int tabIndex);
}

 

There we have a SelectedTab property, and a separate setter method for it, just in case for backup scenario. If you don’t need both then stick to one of them. 😀

2. the TabbedPage…

Alright then let’s get started with our TabbedPage implementation, let’s call it MyTabbedPage.

<TabbedPage
    x:Class="AdvPrismTabNavigation.Views.MyTabbedPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AdvPrismTabNavigation.Views;assembly=AdvPrismTabNavigation"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    Title="{Binding Title}"
    prism:ViewModelLocator.AutowireViewModel="True"
    SelectedTabIndex="{Binding SelectedTab}">
    <TabbedPage.Children>
        <local:TabChild1Page />
        <local:TabChild2Page />
        <local:TabChild3Page />
    </TabbedPage.Children>
</TabbedPage>

 

There’s the XAML code for our MyTabbedPage, notice how we’re binding the SelectedTabIndex property to the ViewModel’s property which I’ll show later in this post. Meanwhile let’s have add some child pages to our MyTabbedPage as well.

Alright next take a look at the MyTabbedPage‘s code behind stuff, which is very minimal.

public partial class MyTabbedPage : TabbedPage
{
	private bool _isTabPageVisible;

	...
        // SelectedTabIndex 
	// bindable property goes here...
	...

	public MyTabbedPage()
	{
		InitializeComponent();
	}
	
	protected override void OnAppearing()
	{
		base.OnAppearing();

		// the tabbed page is now visible...
		_isTabPageVisible = true;

		// go ahead and update the Selected Child-Tab page..
		this.CurrentPage = this.Children[SelectedTabIndex];
	}

	protected override void OnDisappearing()
	{
		base.OnDisappearing();

		// the Tabbed Page is not visible anymore...
		_isTabPageVisible = false;
	}

	protected override void OnCurrentPageChanged()
	{
		base.OnCurrentPageChanged();

		// when the user manually changes the Tab,
		// we need to update it back to the ViewModel...
		SelectedTabIndex
			= this.Children.IndexOf(this.CurrentPage);
	}
}

 

As I mentioned in the recipe, there’s the flag _isTabPageVisible, we’re going to use to keep track of the Visibility of the TabbedPage. There when we’re coming back to the TabbedPage from a backward navigation, we’re executing the selected Child-Tab according to the SelectedTabIndex bindable property.

Important Note: You can even make the above little chunks of code go away from the XAML-Code-behind, by using triggers and attached properties, which I’m not going to get into here, to maintain the simplicity of the implementation. Come on, use your own creativity people! 😉

Next we’re creating the Bindable Property inside the TabbedPage which will handle the View-ViewModel communication. Let’s call it SelectedTabIndex property.

public static readonly BindableProperty SelectedTabIndexProperty =
	BindableProperty.Create(
		nameof(SelectedTabIndex), 
		typeof(int),
		typeof(MyTabbedPage), 0,
		BindingMode.TwoWay, null,
		propertyChanged: OnSelectedTabIndexChanged);
static void OnSelectedTabIndexChanged
	(BindableObject bindable, object oldValue, object newValue)
{
	if (((MyTabbedPage)bindable)._isTabPageVisible)
	{
		// update the Selected Child-Tab page 
		// only if Tabbed Page is visible..
		((MyTabbedPage)bindable).CurrentPage 
		= ((MyTabbedPage)bindable).Children[(int)newValue];
	}
}
public int SelectedTabIndex
{
	get { return (int)GetValue(SelectedTabIndexProperty); }
	set { SetValue(SelectedTabIndexProperty, value); }
}

 

Looks neat eh, so its a simple Bindable property as you can see, but however we’re handling it’s OnSelectedTabIndexChanged event ourselves because when the value changes from ViewModel’s end we need to update it on our UI’s end, as you can see we’re having a little flag property inside our MyTabbedPage 

3. the ViewModel…

Now is the time for MyTabbedPageViewModel stuff to come along. Nothing fancy just a standard ViewModel, but we need a reference to the IoC container (whichever it is you’re using) because we need to register our interface instance in it. This ViewModel as we discussed before is going to implement our IMyTabbedPageSelectedTab interface and its method and property.

public class MyTabbedPageViewModel 
          : ViewModelBase, IMyTabbedPageSelectedTab
{
     private readonly IUnityContainer _unityContainer;

     private int _selectedTab;
     /// <summary>
     /// Binds to the View's property
     /// View-ViewModel communcation
     /// </summary>
     public int SelectedTab
     {
          get { return _selectedTab; }
          set
          {
             SetProperty(ref _selectedTab, value);
             Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";
          }
     }
     
     public MyTabbedPageViewModel
          (INavigationService navigationService,
                         IUnityContainer unityContainer)
          : base(navigationService)
     {
          Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";

          this._unityContainer = unityContainer;

          // register this instance so we can access 
          // IMyTabbedPageSelectedTab anywhere in the code
          _unityContainer.RegisterInstance<IMyTabbedPageSelectedTab>
                    (this, new ContainerControlledLifetimeManager());
     }

     public void SetSelectedTab(int tabIndex)
     {
          SelectedTab = tabIndex;
     }
}

 

The SelectedTab property in the ViewModel is the one that’s binding to the SelectedTabIndex property in the MyTabbedPage, now you can see the bridge between the View-ViewModel.

Here we’re registering this ViewModel instance by the type of IMyTabbedPageSelectedTab so that we can access it from anywhere using the same type and also we’re passing in ContainerControlledLifetimeManager() parameter because we need to make sure that instance is properly managed by the container and garbage collected later when not in use.

4. finally Consume it…

So here is the little Magic code snippet you need to execute, wherever you wish to have access to programatically switching the Selected Child-Tab of our MyTabbedPage.

_unityContainer.Resolve<IMyTabbedPageSelectedTab>().SetSelectedTab(tabIndex);

 

You simply access the registered service interface and call on the SetSelectedTab() or simply you could also call the IMyTabbedPageSelectedTab.SelectedTab property directly as well. 😉

Just a little note, well this may not be the best of all approaches but this is what I believe is a better solution given my experience and expertise. But if you have a better alternative, please feel free to share!

Let’s fire it up!

So here’s this bad boy in action…

 

That’s the Child-Tab being switched programatically while inside the TabbedPage!

 

And here’s how nicely the Child-Tabs are switching programatically while outside the TabbedPage! As you can see when coming back to the TabbedPage, it nicely moves to the Selected Child-Tab…

Eyyy look at that! 😀

How about UnitTest-ing…

Uh fine, let me show you. 😛

In my case I used xUnit.net for my Test project, along side Prism.Forms and Xamarin.Forms.Mocks for mocking Xamarin.Forms run time.

Switching between Child-Tabs inside the TabbedPage:

//  Let's Tab-Navigate to TabChild2Page
_appInstance.Container.Resolve<TabChild1PageViewModel>()
			.GoToNextTabCommand.Execute("1");

//  Am I in the MyTabbedPage-> TabChild2Page?
Assert.IsType<TabChild2PageViewModel>
			(myTabbedPage.CurrentPage.BindingContext);

//  Let's Tab-Navigate to TabChild3Page
_appInstance.Container.Resolve<TabChild2PageViewModel>()
			.GoToNextTabCommand.Execute("2");

//  Am I in the MyTabbedPage-> TabChild2Page?
Assert.IsType<TabChild3PageViewModel>
			(myTabbedPage.CurrentPage.BindingContext);

 

I’m calling the Commands through my child page’s ViewModel and switching the Selected Child-Tab and then asserting to make sure the myTabbedPage instance has updated accordingly.

Switching between Child-Tabs outside the TabbedPage:

//  Am I inside the DetailPage?
Assert.IsType<DetailPageViewModel>
		    (navigationStack.Last().BindingContext);

// Let's go back to Tabbed Page -> TabChild3Page
_appInstance.Container.Resolve<DetailPageViewModel>()
		    .GoBackToTabChild3PageCommand.Execute();

//  Am I inside the MyTabbedPage?
Assert.IsType<MyTabbedPageViewModel>
		    (navigationStack.Last().BindingContext);

//  Am I in the MyTabbedPage-> TabChild3Page?
Assert.IsType<TabChild3PageViewModel>
		    (myTabbedPage.CurrentPage.BindingContext);

 

Here you can clearly see I’m calling the GoBackToTabChild3PageCommand in an page(DetailPage) which Ihave navigated to after the TabbedPage, and what happens in that command is I’m changing the Selected Child-Tab in the MyTabbedPage and immediately going back to it by exiting the DetailPage. Then I’m coming back to the MyTabbedPage, and the Child-Tab 3 is selected in the TabbedPage.

Here’s where you could take a look at the full test implementation : https://github.com/AdvPrismTabNavigation.xUnitTest

Voila! 😀 UnitTest-ing Done!

Github it if yo lazy!

So all of this is hosted on my git repo: https://github.com/AdvPrismTabNavigation

Feel free to grab your copy if you’re too lazy to DIY! 😛

That’s it for today.

Cheers all! 😀 Share the love!

A MVVM-styled Service for my Await-able Custom Input Dialogs (XFCustomInputAlertDialog)

So a lot of folks asked me regarding my previous post, An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! 😉 how they could implement this awesomeness in a MVVM-friendly manner in Xamarin.Forms, instead of having to deal with dirty code-behind ugliness.

Frankly I did the above original implementation in a MVVM-manner, given myself being a MVVM-practitioner, but since there are a lot of newbie Xamarin devs out there, I thought it would help if I push it out there in the simplest manner for the newbies to understand without a hassle.

Anyhow in order to do some justice for the Xamarin-Forms-MVVM practitioners out there, including myself 😉 here I am pushing out how to implement the same awesomeness in Xamarin-Forms MVVM environment in a beautiful code manner! 😀 ❤

Service FTW!

When it comes to dealing with MVVM environments, Services are crucial, which is what we’re going to leverage our previous implementation to.

So we could call up this service from anywhere across our shared code.

This demonstration…

We shall be using Prism as the MVVM framework for this demo Xamarin.Forms project because its awesome! 😉

And create a Service implementation for our XFCustomInputAlertDialog, which we’ll be register with the Prism’s default IoC container.

Rest is pure magic! lol 😉

PS: I shall not be spoon feeding from this post about MVVM or how to set up MVVM framework in Xamarin.Forms, I shall assume you have solid knowledge on MVVM based Xamarin.Forms implementations. 🙂

If you want to be ahead of all, you can grab the Github code from here: https://github.com/UdaraAlwis/XFInputAlertDialogService

Yep this time I’ve created a separate repo for the project. Alright then let’s get started!

Let’s do it…

Taking a step by step approach…

1. Prism MVVM Setup

Add Prism for Xamarin.Forms to your project and do the primarily set up for Prism MVVM framework. (if you’re unaware of how to do this, there’s plenty of tutorials and blog posts online about setting up Prism for Xamarin.Forms)

This also means you’re to set up the Views and ViewModels for the Project. (ex: MainPage -> MainPageViewModel).

2. Set up XFCustomInputAlertDialog basics

There’s few basic things you need to set up from my previous post as follows, and you can go back take a look at that post for these steps,  An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! 😉

  • Setting up Rg.Plugins.Popup library
  • Create InputAlertDialogBase control
  • Create your Custom Input Views as you wish
  • Manage code-behind of your Custom Input Views

That’s it! nothing more! Alright let’s get started off with leveraging to MVVM!

3. Creating the Service…

So we shall create the service for our Custom Alert Dialogs. We shall call it InputAlertDialogService, thereby start off by creating the interface, IInputAlertDialogService with required methods.

namespace XFInputAlertDialogService.Interfaces
{
    public interface IInputAlertDialogService
    { 
        /// <summary>
        /// Open Text Input Alert Dialog
        /// </summary>
        /// <param name="titleText"></param>
        /// <param name="placeHolderText"></param>
        /// <param name="closeButtonText"></param>
        /// <param name="validationLabelText"></param>
        /// <returns></returns>
        Task<string> OpenTextInputAlertDialog(
            string titleText, string placeHolderText,
            string closeButtonText, string validationLabelText);
			
	
	//add other types of dialog open methods from here..
	// Task<string> OpenCancellableTextInputAlertDialog(...)
	// Task<string> OpenSelectableInputAlertDialog(...)
	// ...
	// ...
    }
}

 

You can add any amount of Service method calls to the interface which you can use to implement the concrete implementation.

github.com/XFInputAlertDialogService/…/Interfaces/IInputAlertDialogService.cs

Next let’s create the concrete implementation of our service, InputAlertDialogService.

namespace XFInputAlertDialogService.Services
{
    public class InputAlertDialogService : IInputAlertDialogService
    {
        public async Task<string> OpenTextInputAlertDialog(
            string titleText, string placeHolderText,
            string closeButtonText, string validationLabelText)
        {
            // create the TextInputView
            var inputView = 
               new TextInputView(titleText, placeHolderText,
                   closeButtonText, validationLabelText);

            // create the Transparent Popup Page
            // of type string since we need a string return
            var popup = new InputAlertDialogBase<string>(inputView);

            // Add the rest of Popup 
	    // Dialog display code below...
	    // just as in XFCustomInputAlertDialog
	    // ...
        }

        //add other types of dialog open methods from here..
        // ...
    }
}

 

There we are inheriting from our interface and doing the necessary concrete implementation. You will add the Popup Dialog instantiating and pushing to the navigation stack logic as you did in XFCustomInputAlertDialog code. Since its going to be repeated I’m not going to post the same code snippet here.

You can take a quick peak in the Gitub Repo though 😉

github.com/XFInputAlertDialogService/…/Services/InputAlertDialogService.cs

Then we need to register our Service Interface and Concrete implementation in the Prism’s default Unity Container.

namespace XFInputAlertDialogService
{
	public partial class App : PrismApplication
	{
		public App
		(IPlatformInitializer initializer = null) :
		base(initializer) { }

		protected override void RegisterTypes()
		{
			...
			
			// services registration
		    Container.RegisterType<IInputAlertDialogService,
			InputAlertDialogService>();
		}
		
		...
	}
}

 

There you go, the service layer is now ready! 😀

4. Consuming the Service…

Now let’s consume our Custom Popup Dialog Service in the ViewModel. First let’s inject it to the ViewModel and prepare it to be used when you need it.

public class MainPageViewModel 
	: BindableBase, INavigationAware
{
	private readonly 
	IInputAlertDialogService _inputAlertDialogService;
	
	public MainPageViewModel(
	IInputAlertDialogService inputAlertDialogService)
	{
		...
	
		_inputAlertDialogService = inputAlertDialogService;
		
		...
	}

        ...
}

 

Thanks to the IoC pattern, look at that beautiful and clean code. 😉

Now you’re ready to invoke the awesome custom popup dialogs from anywhere in your ViewModel. Let’s do that as the final step, shall we?

var result = await 
	_inputAlertDialogService.OpenTextInputAlertDialog(
	"What's your name?",
	"enter here...", 
	"Ok",
	"Ops! Can't leave this empty!");

 

If you don’t get the hint, you can simply create a Command in your ViewModel and bind that to a Button or something in your View and add the above call to the Command’s execution method as shown below. 😉

public DelegateCommand 
		OpenTextInputAlertDialogCommand { get; set; }

public MainPageViewModel(
	IInputAlertDialogService inputAlertDialogService)

{
	...
	
	OpenTextInputAlertDialogCommand = new DelegateCommand(OpenTextInputAlertDialog);
	
	...
}

private async void OpenTextInputAlertDialog()
{
	var result = await 
		_inputAlertDialogService.OpenTextInputAlertDialog(
		"What's your name?",
		"enter here...", 
		"Ok",
		"Ops! Can't leave this empty!");
}

 

There you go pure MVVM-Xamarin.Forms goodness! 😀

If you’re one of the lazy you can grab the whole code from Github: https://github.com/UdaraAlwis/XFInputAlertDialogService

Well fellas, that’s it!

Enjoy! 😀 Share the love!

-Udara Alwis 😀