Xamarin

Last friday, thanks to JetBit and to my friend Massimo Bilancia, DotNetSide has organized the first Xamarin Dev Days in Potenza, Basilicata, Italy. What a great day! Meet people, make networking, share development experience in a wonderful location is always the best way to spend a day.

Here, some pictures of the day:

 
Thanks to all the attendees!
Next stop: april 20 @ bari

Read more

La chiara e netta separazione tra la UI e l’application logic è il concetto che sta alla base del pattern MVVM. Molte volte, però, non è semplice capire distinguere le responsabilità, almeno in termini di rappresentazione della UI. Se devo cambiare un colore in base al contenuto, è il ViewModel che lo decide? Dove indico il colore?

Tendenzialmente saremo portati ad aggiungere una proprietà nel ViewModel con l’indicazione del colore da visualizzare. E magari definiamo come tipo della proprietà l’enum Xamarin.Forms.Color. Sebbene semplice, questo approccio è sbagliato perchè assegna al ViewModel una responsabilità della View, oltre al rischio di non rendere il ViewModel compatibile se questo deve essere reso riutilizzabile in diverse piattaforme (non Xamarin.Forms).

Quindi?

Il ViewModel si deve limitare a riportare il dato, senza avere conoscenza del modo in cui esso verrà rappresentato dalla View. Se in una lista di persone dobbiamo mostrare un colore diverso a seconda del sesso, blu per i maschietti e rosa per le femminucce, allora il ViewModel si limiterà a indicare il sesso del contatto visualizzato. Sarà poi responsabilità della View decidere cosa deve essere visualizzato e in che forma.

Una soluzione decisamente elegante e che ci viene incontro in questo contesto è l’utilizzo del DataTrigger.

La via elegante: il Data Trigger

In Xamarin.Forms un trigger permette di definire un’azione al verificarsi di un’evento o al cambio del valore di una proprietà. La sua peculiarità? Possiamo definire tutto in XAML, a livello dichiarativo, senza scrivere una riga di codice. Esistono quattro diverse tipologie di Triggers:

  • Property Trigger: attivato quando la proprietà di un controllo viene impostata su un particolare valore;
  • Event Trigger: attivato quando da un controllo viene generato un particolare evento;
  • Multi Trigger: consente l’attivazione del trigger sulla base della valutazione di più condizioni;
  • Data Trigger: consente di verificare la condizione del trigger, su una specifica proprietà, utilizzando il binding;

Nello specifico scenario, ovviamente, il DataTrigger è il tipo di trigger che fa al caso nostro. Il codice è decisamente semplice. Dobbiamo aggiungere alla collection Triggers di un controllo Xamarin.Forms, ad esempio BoxView, e definire la proprietà del ViewModel da controllare e il valore che quella proprietà deve avere per attivare il trigger. Se la condizione si verifica, viene utilizzato il Setter definito nel trigger per impostare la proprietà BackgroundColor del BoxView su un nuovo colore, Pink in questo caso:

<BoxView.Triggers>
	<DataTrigger TargetType="BoxView" Binding="{Binding Gender}" Value="{x:Static vm:GenderType.Female}" >
  		<Setter Property="BackgroundColor" Value="Pink" />
	</DataTrigger>
</BoxView.Triggers>

 

Questo il codice completo del ListView:

<ListView ItemsSource="{Binding Contacts}" Margin="0,50,0,0">
	<ListView.ItemTemplate>
		<DataTemplate>
			<ViewCell>
				<StackLayout Orientation="Horizontal">
					<BoxView WidthRequest="5" BackgroundColor="Blue">
						<BoxView.Triggers>
							<DataTrigger TargetType="BoxView" Binding="{Binding Gender}" Value="{x:Static vm:GenderType.Female}" >
  								<Setter Property="BackgroundColor" Value="Pink" />
							</DataTrigger>
						</BoxView.Triggers>
					</BoxView>
					<Label Text="{Binding Name}" VerticalOptions="Center" />
				</StackLayout>
			</ViewCell>
		</DataTemplate>
	</ListView.ItemTemplate>
</ListView>

e questo il risultato finale:

Semplice!

Read more

Performance are one of the key features in the app development. If your app is too slow, the users will close it immediately. In this post, you can find some interesting videos from Channel9 about performance optimization of apps builded with Xamarin.

Xamarin.Forms Performance Tips and Tricks

Optimizing App Performance with Xamarin.Forms

Performance Adventures

The Xamarin Show 11: Xamarin Profiler with Nina Vyedin

Just few more links…

Additionally, you can check out some tips and tricks links:

Enjoy!

Read more

Xamarin.Forms is a great way to abstract the local implementation. But, you know, sometimes you need to perform some small adjustments based on the underlying OS. Is this the case of the iOS Status Bar style.

Xamarin.Forms implements, in the NavigationRenderer, a way to automatically set the style (dark/default or light) by checking the Luminosity value of the BarTextColor property. Check the following code:

if (statusBarColorMode == StatusBarTextColorMode.DoNotAdjust || barTextColor.Luminosity <= 0.5)
{
	// Use dark text color for status bar
	UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
}
else
{
	// Use light text color for status bar
	UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;
}

For full code, check the NavigationRenderer source on github Xamarin.Forms project.

Now, if in your code you set the BarTextColor to black, then the status bar style will be the Default (dark). Otherwise, the status bar style will be light (white).

So, if we want to set the BarTextColor, in a classic Xamarin.Forms App class constructor, we’ll have something like this:

public App()
{
	InitializeComponent();

	MainPage = new NavigationPage(new MainPage())
	{
		BarBackgroundColor = Color.FromHex("#043596"),
		BarTextColor = Color.White
	};
}

But, this is not enough.

In iOS, we have two ways to set the StatusBarStyle:

  • at application level
  • at view controller level

The default behavior is at view controller level. Since Xamarin.Forms sets the StatusBarStyle at application level, we need to set the related property in the Info.plist. So, open the info.plist file, go in the Source tab and add a new entry with this values:

Name = UIViewControllerBasedStatusBarAppearance
Type – boolean
Value – No

And we have done! Now start the app and check the result:

Nice and simple!

Read more

This is the third post of the A little and simple Bindable (Horizontal) Scroll View saga. In the first post we saw how to implement a horizontal view with data binding capability. Then, in the second post, we have seen how to add an event to handle the tap gesture on list items.

In this post, we’ll see how to add the Command pattern to the TLScrollView and get working one of the most used way to catch the user UI interaction directly into the ViewModel.

Adding the Command and CommandParameter properties to the TLScrollView

The first step is to add two bindable properties: SelectedCommand and SelectedCommandParameter.

public static readonly BindableProperty SelectedCommandProperty =
	BindableProperty.Create("SelectedCommand", typeof(ICommand), typeof(TLScrollView), null);

public ICommand SelectedCommand
{
	get { return (ICommand)GetValue(SelectedCommandProperty); }
	set { SetValue(SelectedCommandProperty, value); }
}

public static readonly BindableProperty SelectedCommandParameterProperty =
	BindableProperty.Create("SelectedCommandParameter", typeof(object), typeof(TLScrollView), null);

public object SelectedCommandParameter
{
	get { return GetValue(SelectedCommandParameterProperty); }
	set { SetValue(SelectedCommandParameterProperty, value); }
}

The first one will be used to reference the Command object instance, the event handler into the view model, while the second one is the instance parameter that will be passed to the event handler.

After that, we need to modify the TLScrollView Render method to use the new SelectedCommand and SelectedCommandParameter properties, if used:

var command = SelectedCommand ?? new Command((obj) =>
{
	var args = new ItemTappedEventArgs(ItemsSource, item);
	ItemSelected?.Invoke(this, args);
});
var commandParameter = SelectedCommandParameter ?? item;

var viewCell = ItemTemplate.CreateContent() as ViewCell;
viewCell.View.BindingContext = item;
viewCell.View.GestureRecognizers.Add(new TapGestureRecognizer
{
	Command = command,
	CommandParameter = commandParameter,
	NumberOfTapsRequired = 1
});

Use the Command pattern to get the selected item

To use the Command pattern in our solution, we need to add a property in our viewmodel that will be binded to the UI control:

public ICommand ItemSelected { get; set; }

and then initialize it with an event handler in the viewmodel’s constructor:

public MyViewModel()
{
	ItemSelected = new Command(arg => DoSomething());
}

finally we can bind the SelectedCommand property to the ItemSelected property:

<controls:TLScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" SelectedCommand="{Binding ItemSelected}" HeightRequest="100">

Use my ViewModelBase

One step further is to minimize coding by using my ViewModelBase implementation. After extending your custom ViewModel with my ViewModelBase, you can simply write a method with the name ItemSelected and the _ExecuteCommand suffix:

public void ItemSelected_ExecuteCommand(object args)
{
}

After that, you need to add square brackets around the ItemSelected name in your XAML SelectedCommand assignment definition:

SelectedCommand="{Binding [ItemSelected]}"

Nice and really simple. As usual, you can find full code with sample on my github repository.

Read more

A long time ago, in the first post, I wrote about the TLScrollView, a way to create a simple, horizontal and bindable list of items in Xamarin.Forms. The final result is something like the horizontal views on Apple App Store app.

After receiving some feedback, users ask for a way to handle the tap gesture on the items. We have two possible approaches: the first one is by using the classic ItemSelected event handlers, and the second one by using the Command pattern, typical solution in MVVM.

In this post we’ll explore the first approach.

Adding an ItemSelected handler to the TLScrollView

So, first of all, we need to add an ItemSelected event, a delegate of type EventHandler to the TLScrollView:

public event EventHandler<ItemTappedEventArgs> ItemSelected;

Now, in the Render method, we can add the following line in the for..each cycle, just after settings the BindingContext of the ViewCell:

viewCell.View.GestureRecognizers.Add(new TapGestureRecognizer
{
	Command = new Command((obj) =>
	{
		var args = new ItemTappedEventArgs(ItemsSource, item);
		ItemTapped?.Invoke(this, args);
	}),
	NumberOfTapsRequired = 1
});

Now, in your XAML, you can define the handler in this way:

<controls:XScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" ItemSelected="Handle_ItemSelected" HeightRequest="100">

then you can implement your handle:

void Handle_ItemSelected(object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
	// your code
}

That’s really simple! But if you want build a code in line with the Separation of Concern, typical principles of MVVM, a SelectedCommand property should be the best way.

I’ll show the step neeeded to add the command pattern to the TLScrollView in the next post of this series.

Full code is available here

Read more

Last Friday in Bari, DotNetSide has hosted one stop of the Xamarin Dev Days tour in Italy. It was really an amazing day spent with very passionate people talking about Xamarin and how is funny to develop with their tools.

During the day, we talked about Xamarin development with Xamarin.Forms combined with Cognitive Services, Mobile Apps, remote APIs and so on. In the afternoon, a great hands-on lab was made by around 40 people with the intention to share their knowledge (and win a Xamarin monkey! 😀 ).

cygf4_iwgaabjx5

After the announcements made by Microsoft at Connect(); conference last week, we decided to include an extra slot to talk about Visual Studio for Mac, Visual Studio Mobile Center and .NET Standard.

cyghtedxeaafjq5

It was a really great day. I like to see how many people loves their job and try to improve with great passion.

Thanks to all and thanks to the DotNetSiders! You rocks!

Read more

If you are a typical Visual Studio user, you’ll find easy use the menu Debug > Windows > Exception Settings and set your favorite option to break debug when a specific exeption was thrown:

schermata-2016-10-26-alle-21-58-42

But, in Xamarin Studio, that thing is just a little bit different. You need to set a new breakpoint from the menù Run > New Breakpoint:

schermata-2016-10-26-alle-22-02-54

Then you must select the “When an exception is thrown” options:

schermata-2016-10-26-alle-22-04-36

Finally, you can choose the exception that will cause the debugger’s break, eventually by including their subclasses:

schermata-2016-10-26-alle-22-06-18

That’s all!

Read more