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

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 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 :)

2014 was a turbulent year with lots of fun stuff. I finally quit my day job and became a full time freelancer working on Windows Phone, Windows Store, Xamarin and ASP.NET projects. Even though it’s only been a few months, I must say I am enjoying it so far. As usual I gave a few talks at regional conferences, blogged a little, and was renewed as MVP for C# for the second year in a row.

With all that behind me, it’s time to prepare for the future and this post will serve as both a todo list and a reminder for next year’s me. It will be fun comparing what I wanted to do and what I actually managed to do.

Without any particular ordering, here is the grand list of things for the year 2015:

  • Working more on side projects – there are quite a lot of ideas gathered over the year, let’s see which projects are worth pursuing and which projects are not. Hopefully some of them will create some income, but I wouldn’t bet on it. Lots of these side projects include .NET Compiler Platform aka Roslyn in one form or another. If I manage to finish any of ideas based on Roslyn, they might prove beneficial for the community.
  • Startup stuff – yes I know they are all the rage right now. My brother and I joined Core Hub contest with the idea of building scalable real-time platform on .NET. There are some other ideas in the pipeline, mostly about tourism and IT, but those are ideas for this summer/autumn.
  • Blog a little bit more – I should blog more regularly about what I am doing and fun stuff I encounter. I have a bad habit of starting a new series and forgetting all about it. Not anymore! Writing should ease my mind, not add more burden to it. So let’s make that 52 blog posts this year.
  • Games! – ever since I became a programmer I wanted to work in game industry. Actually, creating games was the sole reason for learning programming in the first place. That’s why I decided to join One Game a Month Challenge and see if I can do it. I’ve made zero games so far in my career so let’s make 12 games this year alone :)
  • Open source stuff – most of my side projects/ideas/games can and will be open source. In fact, the first game I am working on this year is already at GitHub and you can check it out here
  • Speaking at conferences – speaking at conferences became a regular thing for me, but there is always next level stuff. This year I will speak about Roslyn at DevWeek conference in London which marks my first conference outside of mainland Europe :)
  • Traveling – so it seems I travel twice a year to USA, once for Build and once for MVP Summit. I want to keep that tradition and I want to add a few more locations around the world if possible. After all, technology does connect us all.
  • Learn a new language – and by that I mean programming language. Since functional programming is all the rage, let’s dive into Haskel and/or F# to see what they can offer.

Well, that will keep me busy :) It will be fun working on any and all of these, but realistically I cannot do all of them. Some things I am already working on. Some things can be combined (open source and games/side projects). The more I manage to do, the better.

So, what is your list for 2015?

Update: the code was updated to support two additional scenarios: inherited classes and classes that cannot inherit DependencyObject<T>.

Writing dependency properties for XAML controls is annoying and contains some redundant parts. Let’s take a look at an example dependency property (generated from snippet):

public static readonly DependencyProperty PropertyTypeProperty = DependencyProperty.Register(
    "PropertyType", typeof (propertyType), typeof (SampleDependencyObject), new PropertyMetadata(default(propertyType)));

public propertyType PropertyType
    get { return (propertyType) GetValue(PropertyTypeProperty); }
    set { SetValue(PropertyTypeProperty, value); }

While the property (at the bottom) itself cannot be simplified anymore, the registration part at the top can be simplified quite a lot. Let’s take a closer look at the necessary parameters:

  • First is the property name which one should never write in string literals. The new feature in C# 6: nameof will help fix that, but for now we are stuck with this.
  • The second parameter is the type of our property, which is already written below and should somehow be inferred automatically. Reflection could help with that, but it’s a heavy artillery and is not an ideal solution here.
  • The third parameter is the type of the enclosing class, a context sensitive information that should be omitted.
  • Finally, in most cases the default value is the default value for the property type.

Our goal here is to remove redundancy, use contextual information and remove string literals all in once. And to shorten our code, of course. Luckily, we can already do that in C# 5 without the upcoming nameof feature and the final syntax for the registration part (the property, unfortunately, stays the same) can be reduced to this:

public static readonly DependencyProperty SampleProperty = Register(d => d.Sample);

read more »