Changing the default binding mode with x:DefaultBindMode

On my Compiled Bindings considerations article, I wrote about the differences between regular bindings (Binding) and the UWP compiled bindings (x:Bind).

The most important bit to keep from that article is the fact that the default binding Mode for regular bindings is OneWay, while for the compiled ones is OneTime.

Best way to understand this is with some sample code:

<StackPanel>
<!-- the implicit binding mode here is "OneWay" -->
<TextBlock Text={Binding Name} />
<!-- the implicit binding mode here is "OneTime" -->
<TextBlock Text={x:Bind Name} />
</StackPanel>

Starting Windows 10 version 1607 (Anniversary Update, SDK version 14393), developers can change the default binding Mode by setting the x:DefaultBindMode attribute.

Applying the attribute to an element will make it and all child elements use the same value for binding mode.

Here’s the same sample code again, now with the x:DefaultBindMode attribute added to the root element:

<StackPanel x:DefaultBindMode="OneWay">
<!-- the implicit binding mode here is "OneWay" -->
<TextBlock Text={Binding Name} />
<!-- the implicit binding mode here is "OneWay", as set on the x:DefaultBindMode in the parent element -->
<TextBlock Text={x:Bind Name} />
</StackPanel>

Migrated from Jekyll to Gatsby

For the last couple of months, I’ve been working a lot on something quite different from my Windows Development expertise: writing .NET Core micro-services with React and Typescript front-end, running on Docker containers in Kubernetes, hosted on Microsoft Azure!

The thing is that the more I worked with React and Typescript, the more I was enjoying it — to the point that made me think on how I could use my new skills on this blog!

Back in 2017, I migrated my blog from WordPress to Jekyll and hosted on GitHub Pages.

From that moment my blog became blazing fast and I was fairly happy with the arrangement; plus, as far as I am aware, I had near-zero downtime on the blog!

However, I always felt that Jekyll in GitHub Pages was quite limited in what can be achieved (a simple example is that you can’t easily generate a page with all categories or tags).

I started to search for a React-based static site generator, and that’s how I found Gatsby!

Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps

A month ago, I started to migrate the blog and today it is all Gatsby based, fully hosted on Netlify (provides free hosting, highly configurable build configuration, custom headers, redirect rules, …)

This very post if the first of many using the new platform!

As far as I can tell, everything is working properly, but if you find any problem, please report it by creating a new issue and I’ll take care of it as soon as possible!

Insider Dev Tour London

Microsoft is hosting the Insider Dev Tour London on June 18th, 2019 from 8:00 to 17:30 at the Vue Cinema in Leiceiter Square.

You can expect a lot of content around building Microsoft 365 experiences (Windows, Graph, Office, Teams), no matter your skill as a developer.

I will be there to talk about “Developing with the new Edge Browser”, and there will be quite a few familiar faces talking about other topics too!

More details and registration are available here!

Making the case for XAML Markup Extensions

Consider the following code:

<AppBarButton Content="Send" Icon="Send" />

In the above example, the AppBarButton.Icon property above is set to “Send” which is actually a value of the Symbol enumeration.

The Symbol enumeration is quite useful to quickly access glyphs from the Segoe MDL2 Assets font file, but this is a limited subset; a more complete list of the available glyphs can be found here.

If you want to use one of the symbols from that list that is not part of the Symbol enumeration, you need to escape the unicode point by prefixing it with ”&#x” and suffixing with ”;“.

For example, the unicode point for the “WindowsInsider” (Ninja Cat) glyph is “F1AD”, so the complete escaped code is ”&#xF1AD;”

In an ideal world, one would just use it like this:

<!-- this doesn't work! -->
<AppBarButton Content="Ninja Cat" Icon="&#xF1AD;" />

However, you will quickly realize that this doesn’t work!

The correct way is by using the FontIcon class and specifying both the font family name and the escaped glyph unicode point:

<!-- this works! -->
<AppBarButton Content="Ninja Cat">
<AppBarButton.Icon>
<FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xF1AD;" />
</AppBarButton.Icon>
</AppBarButton>

MarkupExtension to the rescue!

Introduced in Windows 10 Fall Creators Update (v10.0.16299.0), the MarkupExtension class allows developers to write markup shortcodes just like the native {Binding}, {StaticResource}, or {x:Bind}.

To create a XAML markup extension, create a new class and ensure that it:

  • inherits from MarkupExtension
  • overrides the MarkupExtension.ProvideValue to provide the implementation
  • is marked with the MarkupExtensionReturnTypeAttribute and specifies the return type
  • has a name ending in “Extension”.

Following on our example, we can easily create a MarkupExtension that would return a FontIcon instance for a given glyph unicode point:

[MarkupExtensionReturnType(ReturnType = typeof(FontIcon))]
public class FontIconExtension : MarkupExtension
{
public string Glyph { get; set; }
protected override object ProvideValue()
{
return new FontIcon()
{
Glyph = Glyph,
FontFamily = new FontFamily("Segoe MDL2 Assets")
};
}
}

Having this on our code, we can then use it in XAML just like this:

<!-- this works just fine! -->
<AppBarButton Icon="{local:FontIcon Glyph='&#xF1AD;'}" />

In the end, we went from 5 lines of XAML code to just 1!

Windows 10 Mobile Emulator fails to start with 0x800705AA error

I recently moved to a new machine and while attempting to debug a UWP app in the Windows 10 Mobile emulator, I came across the following error message:

0x800705AA error message
0x800705AA error message

I couldn’t find any information on this 0x800705AA error, but I eventually tracked this to be caused by the fact Hyper-V was using the machine GPU with RemoteFX!

The easiest way to fix this I found was to just disable RemoteFX; to do so, follow these steps:

  • open Hyper-V Manager (just press Win+R, type virtmgmt.msc and hit Enter)
  • on the left pane, right-click the machine name and then click “Hyper-V Settings”
  • on the tree, select “Physical GPUs”
  • untick “Use this GPU with RemoteFX” and click OK

Hyper-V Settings updated
Hyper-V Settings updated

After disabling RemoveFX, remove any Windows 10 Mobile emulator from the “Virtual Machines” list (Visual Studio will re-create these) and just deploy from Visual Studio again and you should now be able to launch the emulator!

Start Strong-Naming your Assemblies!

My opinion on this subject has evolved to the point I’m now recommending that you should strong-name your assemblies.

Why the change of heart?

2 years ago, I wrote my thoughts about strong-naming assemblies in a post I called “Still Strong-Naming your Assemblies? You do know it’s 2016, right?”.

Coming from all the development related pains in Silverlight and Windows Phone platforms, I knew how strong-named assemblies were a real problem, hence why I wrote that post and said that developers should stop strong-naming their assemblies.

With time, that post somehow became the “canonical answer” for questions in the line of “should I strong-name my assemblies?“.

Coming to more recent times, I had the chance to revisit this topic while discussing what to do over a strong-naming related issue on the Windows Community Toolkit.

After the discussion and a few quick checks to confirm the information passed, the consensus was to go ahead and strong-name the toolkit assemblies.

Since that moment, I must admit that I changed my mind and I’m now advocating that you should strong-name your assemblies!

Silverlight and Windows Phone are dead

For much that hurts me to say this(!), Silverlight and Windows Phone are dead platforms and thus, the reasoning to not strong-name an assembly as they could become unusable in these platforms, is no longer valid.

Modern frameworks can ignore strong-name information

While Windows 10 UWP and Xamarin completely ignore any strong-name information in the referenced assemblies, .NET Core has mechanisms to automatically redirect all references.

In fact, .NET Core enforces all their assemblies to be strong-named (they even have a document describing this requirement).

NuGet does help by automatically creating binding redirections when you add packages to your project!

Yes, against what I thought to be true, Windows 10 still has a GAC that supports side-by-side assemblies for the full .NET Framework!

The GAC requires strong-named assemblies, so there is still a real use case for those in modern days.

Final thoughts

I’m taking a leap of faith that all currently supported frameworks and all future ones will provide mechanisms to ignore strong-name info in assemblies, or just allow to use redirections.

If that proves true, then yes: you should strong-name your assemblies as that will allow more people to use them.

To those still skeptical of strong-naming their assemblies, I propose a compromise solution: do strong-name your assemblies, but only increment the assembly version for major releases! Json.NET has been using this approach to avoid binding redirects since 2014, and as far as I can tell, with relative success!

As a final note to open-source library developers, I strongly recommend that the strong-name key file gets check-in to the project repository so that anyone can easily clone the project and compile a version of the library that works with anyone else’s binaries!

Building multi-window dispatcher agnostic view-model

On my earlier post I wrote about “Building a dispatcher agnostic view-model”; that was just laying the ground for this follow up post, where I am going to show how we can extend that knowledge to use view-models shared between separate windows on different UI threads!

In truth, I started thinking in writing this after seeing my fellow MVP Rudy Huyn CrossUIBinding library.

Rudy’s solution to this problem requires a wrapper around the properties of the view-models, where as I intend to fix the way view-models notify their event handlers.

But why do I need this?

Well, you will only need this if your application uses multiple windows and you want to share the same view-model instance between them!

if that is the case, then you must ensure you raise the INotifyPropertyChanged.PropertyChanged event on the correct thread as each window as its own separate UI thread!

I strongly recommend a look at the great document that Rudy has written around the CrossUIBinding as it has a lot of valuable information with some great visualizations!

So how do we solve this?

We can ensure we raise the PropertyChanged event in the correct UI thread by capturing the dispatcher instance when an event handler is added!

That can easily be achieved by defining custom add and remove event accessors that will get invoked when client code subscribes and unsubscribes respectively to the event:

public abstract class MultiWindowBaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
{
add
{
// add code goes here
}
remove
{
// remove code goes here
}
}
}

All we now need is to ensure we capture the CoreDispatcher when the add method runs, and store that with the handler reference.

After my first post, Daniel Vistisen correctly pointed out that we can use SynchronizationContext instead of CoreDispatcher thus making the whole thing .NET Standard compliant:

He is absolutely right, so that is what we will now do!

We will use a Dictionary<SynchronizationContext, PropertyChangedEventHandler> to keep a collection of event handlers for each SynchronizationContext.

In the end, this is what I got to:

public class MultiWindowViewModelBase : INotifyPropertyChanged
{
private readonly object _lock = new object();
private readonly Dictionary<SynchronizationContext, PropertyChangedEventHandler> _handlersWithContext = new Dictionary<SynchronizationContext, PropertyChangedEventHandler>();
public event PropertyChangedEventHandler PropertyChanged
{
add
{
if (value == null)
{
return;
}
var synchronizationContext = SynchronizationContext.Current;
lock (_lock)
{
if (_handlersWithContext.TryGetValue(synchronizationContext, out PropertyChangedEventHandler eventHandler))
{
eventHandler += value;
_handlersWithContext[synchronizationContext] = eventHandler;
}
else
{
_handlersWithContext.Add(synchronizationContext, value);
}
}
}
remove
{
if (value == null)
{
return;
}
var synchronizationContext = SynchronizationContext.Current;
lock (_lock)
{
if (_handlersWithContext.TryGetValue(synchronizationContext, out PropertyChangedEventHandler eventHandler))
{
eventHandler -= value;
if (eventHandler != null)
{
_handlersWithContext[synchronizationContext] = eventHandler;
}
else
{
_handlersWithContext.Remove(synchronizationContext);
}
}
}
}
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
KeyValuePair<SynchronizationContext, PropertyChangedEventHandler>[] handlersWithContext;
lock (_lock)
{
handlersWithContext = _handlersWithContext.ToArray();
}
var eventArgs = new PropertyChangedEventArgs(propertyName);
foreach (var handlerWithContext in handlersWithContext)
{
var synchronizationContext = handlerWithContext.Key;
var eventHandler = handlerWithContext.Value;
synchronizationContext.Post(o => eventHandler(this, eventArgs), null);
}
}
}

Now all we need is to ensure that any view-model used on multiple windows, inherits from this base class.

Here’s a really simple example:

public class MainViewModel : MultiWindowViewModelBase
{
private string _text;
public string Text
{
get { return _text; }
set
{
if (_text == value) return;
_text = value;
OnPropertyChanged();
}
}
}

Final thoughts

The ApplicationView.Consolidated event should be monitored to allow for proper cleaning, so that no memory leaks occur.

Here’s an example of how this can be achieved:

public sealed partial class MainPage : Page
{
public MainViewModel ViewModel => App.MainViewModel;
public MainPage()
{
DataContext = ViewModel;
this.InitializeComponent();
ApplicationView.GetForCurrentView().Consolidated += ApplicationView_OnConsolidated;
}
private void ApplicationView_OnConsolidated(ApplicationView s, ApplicationViewConsolidatedEventArgs e)
{
if (e.IsAppInitiated || e.IsUserInitiated)
{
s.Consolidated -= ApplicationView_OnConsolidated;
DataContext = null;
// this is only required if you are using compiled bindings (x:Bind)
Bindings.StopTracking();
}
}
}

I’ve also made available a full sample on GitHub so you can see and test the whole solution! :)

Building a dispatcher agnostic view-model

If you are writing multithread Windows apps (and if you are not, you should!), you know by now that any code related to the UI must run in the main thread (also called UI thread).

Knowing this, please look at the following view-model:

// Basic implementation of the INotifyPropertyChanged interface
public abstract class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// The main view-model
public class MainViewModel : BaseViewModel
{
private string _result;
public string Result
{
get { return _result; }
set
{
_result = value;
OnPropertyChanged("Result");
}
}
public async Task RetrieveData()
{
var data = await GetDataFromSomeWebsite()
.ConfigureAwait(false);
Result = data;
}
// More code will go here...
}

The BaseViewModel is just a basic implementation of the INotifyPropertyChanged interface with a helper method that will raise the PropertyChanged event - all quite standard for any MVVM based application!

Now let us say that in the view we have a TextBox control, and that the Text property is binded to the MainViewModel.Result property.

Given this, you will probably notice a problem with the MainViewModel.RetrieveData method: after awaiting the call to GetDataFromSomeWebsite method, most likely we will not be on the UI thread due to the .ConfigureAwait(false) (if you dont know what ConfigureAwait is, please read this post). So, when we set the Result property on the next line which in turn will notify the UI that the property value has changed, that will cause an exception!

To fix it, we can use CoreApplication.MainView.Dispatcher to retrieve a CoreDispatcher instance that will then allow us to execute code in the UI thread.

With some minor changes, the MainViewModel.RetrieveData method now looks something like this:

public async Task RetrieveData()
{
var data = await GetDataFromSomeWebsite()
.ConfigureAwait(false);
CoreApplication.MainView.Dispatcher(CoreDispatcherPriority.Normal, () =>
{
Text = data;
});
}

For small view-models this approach is perfectly fine, but for bigger ones where multiple developers are working on, you might end up losing track of which properties you need to update in the UI thread and the ones you do not.

Wouldn’t it be great if you just didn’t have to worry about this?

To make our view-models completely oblivious of what is the current thread, we will need to make some changes to their base view-model!

The easiest way will be to capture the CoreDispatcher at start, and on the OnPropertyChanged method (or whatever you called your PropertyChanged event raising helper method), check if we need to dispatch the call or just raise the property regularly.

Here is our new and improved BaseViewModel:

public abstract class DispatcherAgnosticBaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private CoreDispatcher _dispatcher = CoreApplication.MainView.Dispatcher;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (_dispatcher.HasThreadAccess)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
else
{
_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
});
}
}
}

Notice that the first this we do is to check the CoreDispatcher.HasThreadAccess property; this property will return true if we are now on the UI thread, or false if we are not.

If we are, we can just raise the PropertyChanged event directly, but when we are not, we will do it by dispatching the call through the UI thread.

Now all we now need is to have every single view-model to inherit from this base class and we will never have to worry again about the dispatcher!

Well… not interely accurate, but I’ll leave that for another post ;)