Resolving "UIWindow does not contain a definition for Current" issue in Uno Platform

Uno Platform

4 years ago

One of the common issues I have seen developers have when porting their UWP apps to Uno Platform is the following error:

Error CS1061 'UIWindow' does not contain a definition for 'Current' and no accessible extension method 'Current' accepting a first argument of type 'UIWindow' could be found (are you missing a using directive or an assembly reference?)

This error can occur when we refactor the App.xaml.cs class based on Visual Studio IntelliSense suggestions by removing the full namespace qualification before the Window.Current usages. For example from:

To:

This refactoring seems harmless, but that "harmlessness" depends on the context we are currently in. For UWP, Android and WASM platform targets, we get no error in the source code, but when we switch to iOS in the platform dropdown:

Switching to iOS platform in platform target dropdown

Switching to iOS

Now, suddenly, we get the red squiggle:

Red squiggle is here!

Red squiggle is here!

The reason is the Window in App class for iOS does not refer to Uno's implementation of Windows.UI.Xaml.Window, but to a Window property of type UIWindow. Where does this property come from? The answer lies in the way the Windows.UI.Xaml.Application class is implemented in Uno Platform for iOS. When we take a peek into the source code on GitHub, we can see the class is declared as follows:

Therein lies the crux of the problem. iOS UIApplicationDelegate contains a Window property for application window manipulation, so when any code within a class that inherits from Application refers to Window, the property implicitly gets precedence over Window type name, as per C# language rules. Fix is quick - use full namespace qualification, hence Windows.UI.Xaml.Window, whenever we want to work with UWP/Uno window. There are other areas where an analogous problem can occur on other platforms, too. I have encountered this for on Android when porting code with dragging events. The DragEventArgs class on Android is declared as a nested type of the Android.Views.View class, which is essentially the ascendant of all Uno controls on Android. Due to this, it clashes with UWP/Uno Platform DragEventArgs type:

DragEventArgs on Android

DragEventArgs on Android

The fix is again to fully qualify the type as Windows.UI.Xaml.DragEventArgs.

Summary

Uno Platform apps target multiple platforms, so it always helps to keep the target platform dropdown in mind. Whenever we encounter an error, which prevents compilation but does not show up in code, it can help us see the exact source of our problem.