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 »

Converters are an essential building block in XAML interfaces with one simple task: converting values of one type to another. Since they have a input, usually a view model property, and an output, it would be wonderful if we could somehow chain them to create a new converter that processes all internal converters. Luckily, this is quite simple to do, but we do need to create a new converter which will hold other converters and whose implementation will iterate over nested converters. Full code can be found over at Github repository here, only interesting parts will be highlighted in this blog post.

Our combining converter class is also a converter itself, but it can contain other converters inside it:

public class ChainingConverter : IValueConverter
	public Collection<IValueConverter> Converters { get; set; }

Converter functions are trivially implemented and iteratively go through the converters list and apply the converter on the previous value.
read more »

When it was introduced, LINQ to Objects brought something very interesting to C# world – fluent API. Take a look at the following code:

var result = list.Where(i => i.Extra != null)
                 .Select(i => i.Extra)

Ignoring the types of objects involved, the underlying algorithm, nay, the purpose of this code is visible at a glance. We take the list of objects, extract only those that satisfy the given condition, create a projection, cast to a new type, filter out null values, and finally create the resulting list.

Working with collections allows method chaining because all methods are actually defined as extension methods on IEnumerable<T>. Chaining is something we are also used to when dealing with objects. Calling a member function or changing the property of a property is a simple matter of typing dot, writing member name, typing dot again, etc.

In case you are a fan of that coding style, you might find the following code slightly annoying to write:


Why would that be annoying, that is perfectly legal C#! And quite common actually. To better understand the source of frustration, let’s see how one would arrive at such code.
We start with innocent variable foo of some type. It is irrelevant which type it is and all we know at that point is that we want to invoke the method cleverly named Invoke on it. However, after typing dot, we realise that foo is actually an instance of some other type and that we need to cast it first to get to an appropriate type. Let’s ignore type checking and presume that we know that foo is indeed what we need (e.g. attached properties in XAML platforms have this pattern; even though it is an object, you know what type it is).

So have the following code currently on the screen at that moment:


To cast foo to an appropriate type from we need to add go back to the beginning of the expression and add two left braces, the appropriate type, right brace, go to end of the expression, put the brace just before the dot and then move cursor to the right and we can now find Invoke in our auto complete list.

This little process disrupts our natural flow. It would be so much easier if we could somehow continue typing to the right of dot once we realise that our variable is not of the correct type.

Something like:


read more »

One can argue that BooleanToVisibilityConverter is rooted deeply in the XAML-based platforms. It is the simplest IValueConverter one can implement and you can find it implemented in various toolkits, frameworks or simply reimplemented time and time again by developers. Part of the reason is that the default facility for showing and hiding is unbindable to regular boolean property.

Historical reason for this can be found in WPF where controls can be in one of the three following states: Visible, Hidden, and Collapsed. When Silverlight was introduced, the Hidden state was removed and only two possibilities existed and which correspond to boolean states.

However, the syntax is atrocious. Look at the following example:

Visibility={Binding IsVisible,
                    Converter={StaticResource BooleanToVisibilityConverter}}

Imagine writing that every time you need to hide a control? Well, you just imagined a lot of code out there.

So, how can we fix this and shorten the syntax? By using attached properties of course. Even though there is no such thing as an IsVisible property, it doesn’t mean we cannot invent one ourselves. The final syntax appears similar to this one:

common:Alt.IsVisible={Binding IsVisible}

Isn’t that much readable? Both the namespace and the owner class names can be shortened to get an even shorter syntax.

Here is the implementation:

/// <summary>
/// Definition of alternative attached properties for various
/// controls.
/// </summary>
public static class Alt
	public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
		"IsVisible", typeof(bool?), typeof(Alt), new PropertyMetadata(default(bool?), IsVisibleChangedCallback));

	private static void IsVisibleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		var fe = d as FrameworkElement;
		if (fe == null)

		fe.Visibility = ((bool?)e.NewValue) == true
			? Visibility.Visible
			: Visibility.Collapsed;

	public static void SetIsVisible(DependencyObject element, bool? value)
		element.SetValue(IsVisibleProperty, value);

	public static bool? GetIsVisible(DependencyObject element)
		return (bool?)element.GetValue(IsVisibleProperty);

The source code and the accompanying sample project can also be found on the Github repository here: github.com/MassivePixel/wp-common.

In case you haven’t heard the news, the new version of Visual Studio is out: Visual Studio 2015 Preview. You can grab it here. With you’ll get:

  • A new version of C# language currently at version 6
  • .NET Compiler Platform formerly known as Roslyn: the new compiler for C# and VB.NET which is open source and exposes quite a lot of the underlying infrastructure for the user
  • New JIT compiler i.e. RyuJIT which is also open source
  • Open source subset of .NET Framework

Small things really :) This post will focus on the new features in C# 6 which can both shorten your code and make it more understandable. So let’s begin. In fact, only a couple of new features can be used to add more code to your existing code base.

Class properties enhancements

Writing immutable classes is relatively hard in C# and a few small additions to the language make things easier. Take a look at the following class: read more »

MVP goodies :)

It was April 1st, but the mail was real – I was re-awarded the MVP status for Visual C#. It was about time I replace the stickers on my devices anyway :) I hope that this year will be filled with more C# development now that Roslyn is officially available.

Speaking of Roslyn, the real shocker was the announcement at last week’s Build conference about Roslyn being open source. Wow, this will have a great impact on open source community in .NET world. If only .NET Native is open source (asking for open source .NET itself is a long shot), that would open the flood gates towards other platforms in no time. Even though everyone claimed .NET is dying or being abandoned just a year ago, at Build we had a chance to see the beautiful future for .NET.

Pictured: beautiful .NET future

Pictured: beautiful .NET future

This week I had two sessions at WinDays and NTK about the future of C# and awesome things you can do with Roslyn. Next week I am talking about app to app communication between Windows Phone and Windows Store applications at MS Network. I have to mention that all three conferences are held in beautiful locations in this region: Umag, Bled and Banja Vrućica.

Happy coding :)

This is definitely the coolest thing I found today: running XNA in Visual Studio 2013. Thanks to the unofficial contribution, it is possible to use XNA 4.0 in Visual Studio 2013, 2012 and 2010. Find the appropriate download links at codeplex.

This brings XNA development back in the latest version of Visual Studio, but sadly, although you can develop Windows Phone 7 XNA games in VS 2013, you cannot deploy them from Visual Studio since it doesn’t support WP 7. But that can be fixed since the final XAP is valid and XapDeploy can be used to deploy built games to emulator.

XNA 4.0 running from Visual Studio 2013

XNA 4.0 running from Visual Studio 2013

So as XNA projects can be loaded in the same solution as MonoGame projects, porting old games will be easier. Since the project promises porting XNA to DirectX 11, we now have two projects with same scope in mind.

The next release of C# is on its way and brings cool new features. One very popular request is the ability to initialize automatic properties, those without an explicit backing field, to some value without resorting to constructor. You could vote on the UserVoice here. Here is the proposed syntax:

public int X { get; set; } = x;

And if you need readonly properties:

public int Y { get; } = y;

Although a small change, this can clear up the code significantly.

TL;DR it cannot be done. But, if you have access to the application’s source code, there is a small workaround.

So, why would we want that in the first place? UI automation is not as uncommon as one would think. Its primary use is for creating UI tests for which you need the ability to simulate clicks.

So, how does one simulate click on UI elements? By using a derived class from System.Windows.Automation.Peers.AutomationPeer.

But there is no such class for ApplicationBarIconButton and there is no way for us to manually invoke click events. Usually we could use reflection for this purpose, but platform security forbids us from accessing private methods and fields so that goes out of the window.

Luckily, we can create our own class that inherits ApplicationBarIconButton and exposes such function. It is pretty short code to write actually:

public class ApplicationBarIconButton : ApplicationBarIconButton
    public new event EventHandler Click;

    public void RaiseClick()
        if (Click != null)
            Click(this, EventArgs.Empty);

And that’s it, just replace every regular ApplicationBarIconButton with this in XAML and you are done. In your testing framework find buttons, cast them to this type and call RaiseClick.

Note that this won’t actually work if you are using some bindable replacement for the regular binding-unfriendly


I wrote about some advanced techniques for adapting Windows Phone UI for big screens and 1080p resolutions on Nokia’s Developer Wiki: Advanced Techniques for Big UI. The article was written as a part of Nokia Imaging and Big UI Wiki Competition 2013Q4 which ended two days ago. There are great entries in this competition and I recommend reading them if you want to become familiar with Nokia Imaging SDK 1.0 and developing applications for the big screen.

Here is an introduction:

Designing applications for Windows Phone 7.x (from now on WP7) was easy since there was only one supported resolution – 480 x 800 (WVGA). In addition, screen sizes did not vary that much between vendors. This “un-fragmentation” was hailed as a great feature for the young OS since applications would look the same on all devices that ran Windows Phone 7.

Windows Phone 8 introduced two additional resolutions: 768 x 1280 (WXGA) and 720 x 1280 (720p). The first is an up-scaled version of the original resolution and they share the same aspect ratio (15:9). The latter resolution actually has a different aspect ratio (16:9). This meant that applications had some extra space at the bottom for the UI, but in general if layout is done dynamically, UI does not need to be altered significantly to account for the extra space. The devices got a little larger, but this also meant little to the application design process.

However, coming with GDR3 update, Windows Phone 8 got a new resolution – 1080p. Along with the new, and currently the highest available, resolution, devices also grew in size. For the first time Windows Phone 8 is ran on devices with 6 in screen diagonal. Applications can no longer simply scale up to accommodate such large devices, they need to change their layout a bit as well.

This article presents a couple ideas for adapting the application’s UI for the large screen. It also contains some helper classes useful for detecting current resolution and current screen size. There is also a small trick used here to use 720p emulator image as a 1080p device with “faked” screen diagonal of 6. This allows for easy testing of mentioned techniques without having a physical device with either 6 screen diagonal or 1080p resolution.

Read more on wiki page.