Skip to main content

Detecting binding errors with LogWarningsToApplicationOutput in Xamarin.Forms

·3 mins

In a previous blog, which can be read here, I already described how you can detect binding errors in Xamarin.Forms. As a result of that blog, I opened a pull request on the Xamarin.Forms repository to add this as a feature instead of a hack. Let me tell you about this new upcoming feature in Forms, the LogWarningsToApplicationOutput.

The Issue #

This is the problem that is described in the initial issue by user pingzing as:

In Xamarin.Forms, when a {Binding} expression fails, it fails silently, and at runtime. The only indication that the binding has failed is that nothing appears in the UI. Debugging this can be difficult–is it a BindingContext issue? A typo in my property name? Did I accidentally define my property as a member variable? Etc.

Pingzing already did some investigation and found that there actually was some logging going on. But that logging was not propagated to the end-user, being Xamarin.Forms developers in this case. I was triggered by this issue and wanted to get this baked into Forms by default.

The Process #

Working together with pingzing, we quickly created some great code with event handlers and everything. With that, you could hook up your own logging mechanism and detect the errors. You can see how it all went in the PR page. As you can see, we over-engineered it and the guys at Microsoft had a different approach in mind. They suggested to simply add one property which adds or removes a debug logging listener. That is how I eventually implemented it, which results in the Application.LogWarningsToApplicationOutput.

Using LogWarningsToApplicationOutput #

Now, the important part. How do you use this new property?

It is fairly easy, on the Application class, there is now a new boolean property LogWarningsToApplicationOutput. Setting this property to true, under the covers a new LogListener is added to the existing logging mechanism in Xamarin.Forms. This listener will simply do a Debug.WriteLine which results in outputting the message in your debug output window. You can see a sample result, with a binding error, below.

Binding errors in the output window

You can set LogWarningsToApplicationOutput at startup of your app:

public App() { Application.LogWarningsToApplicationOutput = true;

InitializeComponent();

MainPage = new MainPage();

}

In the GitHub issue, there is even some talk that it can be included in the default template in the future.

Besides the binding errors, that are the most annoying in my opinion, logging now probably includes other errors as well.

This feature will probably be part of Xamarin.Forms 3.2 of which the first preview is out now. Keep your eye on the release notes page! If you want to see your binding errors right now, have a look at the sample repository: https://github.com/jfversluis/BindingFailureOutputSample