If you want to build Windows 10 applications in F#, send your thoughts and vote for F# support in .NET Native for UWP.

MVVM and XAML play really well together. Main building block for building UIs in XAML is the ability to bind with view models (VM in MVVM, we are talking about half of the pattern here). One way or two way binding, it doesn’t matter. Your logic can update properties and UIs will magically refresh.

Bindable object and its properties

XAML expects view models to satisfy certain criteria to achieve that binding. Classes which implement INotifyPropertyChanged are considered bindable and any change to the underlying property must use notifications to correctly notify XAML that value needs to be fetched again.

Consider this small view model:

public class UserViewModel : INotifyPropertyChanged
	// Implementing INotifyPropertyChanged
	public event PropertyChangedEventHandler PropertyChanged;
	// Cache across instances
	private static readonly PropertyChangedEventArgs NameChangedArgs
		= new PropertyChangedEventArgs(nameof(Name));
	private string _name;
	public string Name
		get { return _name; }
			if (_name != value)
				_name = value;
				PropertyChanged?.Invoke(this, NameChangedArgs);

read more »

Inspired by Greg Shacles’ FloatLabeledEntry I wanted to see how easy (or hard) it was to bring similar effect to UWP apps. This is the result:

Floating TextBox Header

Flying TextBox Header

TextBox already has a header in its template which is always shown. This helps us and we don’t have to create custom control, we can just alter the default style. For the above effect, the header had to be hidden by default and shown once user starts typing. This can be done easily just by changing the animations in the visual states. We will change the default template for TextBox which can be easily extracted in Visual Studio.

First, change the HeaderContentPresenter by setting the opacity to 0 and add RenderTransform.

	<TranslateTransform Y="25" />

Now, we want to animate header once the user starts typing. To do that, edit the Focused visual state and add the following animation:

<DoubleAnimation Storyboard.TargetName="HeaderContentPresenter"
				 To="1" Duration="0:0:0.25"
<DoubleAnimation Storyboard.TargetName="HeaderContentPresenter"
				 To="0" Duration="0:0:0.25"
		<SineEase EasingMode="EaseOut" />

And since we want the animation to reverse when the focus is lost, we should add transitions:

	<VisualTransition From="Focused"

And we are done. This is rather simplistic approach and we still need to tweak font properties a bit, maybe animate placeholder text as well. But that is left as an exercise for the reader. You can find the full code for the final style in gist https://gist.github.com/tpetrina/924dba9f93ebf105b221.

One of the best features that come with the brand new compiler API-s for C# and VB.NET is the scripting support. While not in its final form, it’s already quite usable. So let’s see it in action.

First, pull the latest sources from the official Roslyn repository and build them. The binaries should be in Binaries/Debug.

Next, open Visual Studio and create a simple Console application using .NET 4.6. Add references to the following dlls:

  • Microsoft.CodeAnalysis.Scripting.CSharp.dll
  • Microsoft.CodeAnalysis.Scripting.dll
  • Microsoft.CodeAnalysis.CSharp.dll
  • Microsoft.CodeAnalysis.dll
  • System.Reflection.Metadata.dll

The following code will create a new script with the code “Hello World”, evaluate it asynchronously and write out the result.

var script = CSharpScript.Create("\"Hello world\"");
var result = script.RunAsync();

	.ContinueWith(t =>


This is a simple as it gets. In our next post we’ll build a simple REPL :)

Get the source here.

The latest trend in application framework development is the introduction of more functional and immutable data structures. Common arguments for functional approach are better readability, less bugs and easier testing. Traditionally, C# code is highly mutable although language does allow creating immutable classes. Most C# developers don’t know that mutable structures are evil although they are using immutable structures almost daily (e.g. DateTime).

MVVM as a prevalent pattern for building XAML applications is far from functional and/or immutable. Most examples and frameworks focus on ease of development not in terms of long term application stability and architecture, but rather focus on creating apps quickly thus reducing development time. By doing developers are sacrificing time spent now for time spent fixing bugs in the future.

One easy and quick approach towards building better view models is to make them as readonly as possible. It is fairly difficult to write immutable structures in C# the way F# or other functional languages do it, but moving from fully read/write to readonly structures brings some benefits of immutability and predictability to C#.

Rule #1: private setters for commands and bindable properties

Unless your property is writeable from UI i.e. you are using two way binding, the setter should private. Doing so might produce compiler errors, but you are now discovering who is writing over your setters which might help you narrow down bugs. Such errors make dependencies obvious since now external code cannot easily overwrite values and you might enforce better contracts for changing any values.

Default snippet for creating properties prop creates properties which are mutable from the outside:

public TYPE Type { get; set; }

This might explain why properties with public setters are so prevalent. It is just too easy to create them.

Rule #2: Use structs or initialise everything in constructors

Since modifying properties becomes impossible after implementing rule #1, any previously writeable property should now be initialised from the constructor and changed via commands or public methods.

If your view model contains no writeable properties and no methods change the internal state, you can change class into structure. Now you have immutable view models.

Rule #3: Use ReadOnlyObservableCollection instead of ObservableCollection

Observable collections are great since they allow you to bind changeable lists to your UI. But doing so exposes your list to outside code and you have no way of knowing who and when changes your list. This might introduce bugs at some point.

Since UI controls usually require your lists to implement IEnumerable for fetching items and INotifyCollectionChanged for collection change notifications, exposing raw and mutable collection is more than you need to expose in the first place.

ReadOnlyObservableCollection is a wrapper around ObservableCollection instance which allows view models to change the underlying collection. Change events are correctly propagated from the private collection through the readonly one. Exposing lists as readonly only prevents the outside code to directly modify collections, the internal code can still change it.

Here is an example showing how to use ReadOnlyObservableCollection:

public class MainViewModel
	private ObservableCollection<string> _items;
	public ReadOnlyObservableCollection<string> Items { get; private set; }

	public ICommand AddCommand { get; private set; }

	public MainViewModel()
		this._items = new ObservableCollection<string>();
		this.Items = new ReadOnlyObservableCollection<string>(_items);

		this.AddCommand = new RelayCommand(Add);

	private void Add()

Rule #4: Use ReadOnlyCollection instead of List

For static lists inside view models, expose readonly view instead of mutable List. The usage is similar to the example above.


Restricting outside access to classes’ properties exposes flaws in codebase and prevents bugs. Knowing when an object is changed and who can change it is extremely valuable information. While not a pure immutable approach, readonly approach is one step in the right direction.

More than two years ago I wrote about how you should never write asynchronous methods that return void. Writing asynchronous code became the norm and we should revisit key points about writing asynchronous functions.

Here are a couple of guidelines when writing asynchronous code in C#:

  1. Always add suffix Async to the end of the method. Readability beats terseness in this case.
  2. Always return either Task or Task<T>.
  3. If you really have to write async void function e.g. when implementing an interface or adding an event handler, consider wrapping the code in try-catch and handle exceptions that way.
  4. Handle TaskScheduler.UnobservedTaskException.

Keep in mind that handling exceptions even when method returns Task is something that you have to keep in mind.

This is first post in the series describing the navigation pattern in XAML based application. The series will focus on problems and solutions that arise when using MVVM (Model-View-ViewModel) and XAML. Even though they are meant to be used together, the MVVM pattern does not solve navigation completely nor correctly.

WPF and Silverlight: introduction

Windows Presentation Foundation was introduced almost 10 years ago. Besides introducing a new and beautiful way of creating UI declaratively, it also introduced a new pattern based on the powerful data binding mechanism: MVVM. Since it was born on desktop, WPF applications consisted of windows and dialogs.

A few years later we got Silverlight: a version of WPF (also known as WPF/E where E stands for everywhere) trimmed down and optimized for the web. Due to its architecture and the fact it was used in browsers, it also introduced a navigation stack and navigation capabilities. Its primary purpose was mimicking how browsers navigate from one page to another. The Frame contained Pages and navigation was done through (mapped) URIs. Using URIs for navigation had one serious implication: when navigating from one page to another, you could only send strings, or objects that can be converted to strings, through the query string. read more »

Xamarin.Forms are awesome for building applications, but eventually you have to get dirty and fix platform specific issues. And once down there, one quickly realizes that native development is not so much different than native development for that platform itself.

Let’s take a look at the relatively simple problem with iOS: changing the unselected color for the tab bar icons. Searching the web brings us to the den of programming solutions, Stack Overflow, with the following solution http://stackoverflow.com/questions/11512783/unselected-uitabbar-color. The code is straightforward:

UIColor * unselectedColor = [UIColor colorWithRed:184/255.0f green:224/255.0f blue:242/255.0f alpha:1.0f];
item.image = [[item.selectedImage imageWithColor:unselectedColor] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

read more »

If you are using Xamarin Forms for your next awesome cross-platform mobile app, there are things you need to remember when dealing with images for Android.

1. No folders

Even though you can group images into subfolders at root level for Windows Phone or under Resources for iOS, all images have to be inside the Drawable folder for Android. Images in folders are not used.

However, Images/picture.png still resolves on Android.

Which brings us to the obvious…

2. No duplicates

You cannot have two images with the same name in two different folders like Company1/Logo.png and Company2/Logo.png.

Because you cannot have two files with the same name in the same folder.

However, there are still problems with file names…

3. Invalid characters in file names

After reading point 2, you renamed your files and put all images into Drawable. You renamed those files with the same name to something more obvious like Company1-Logo.png and Company2-Logo.png. And it still doesn’t work.

// aapt resource value: 0x7f020020
public const int Icon = 2130837536;

Picture above: Android’s awesome resource handling code.

Due to the way resources are processed in Android, all file names are converted to C# identifiers. And you can resolve images by using their C# counterpart. This, unfortunately, means that only those file names which are valid C# identifiers are valid file names.

This means removing dashes and using underscores. This also means that your images starting with numbers are also invalid. Forget all those 1.png and 13thStreet.pngh, use some “better” names.

Till’ next time, happy coding.

This advice is no longer valid as of Xamarin.Forms 1.3.3. The current implementation for the ObservableCollection fixed this bug.

Xamarin.Forms are awesome, but the framework is young and there are some very annoying bugs. Consider the following common, and simple, scenario: you have a ListView bound to an ObservableCollection. If you want to clear/fill that list, e.g. you are building a search page, you will get the following errors (the numbers may vary):

MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

There is a simple workaround: clear the list by removing each item individually. Instead of writing:



while (list.Any())
    list.RemoveAt(list.Count - 1);

Happy coding :)