Version adaptive code

02/08/2017

12 minutes to read

Contributors

In this article

You can think about writing adaptive code similarly to how you think about creating an adaptive UI. You might design your base UI to run on the smallest screen, and then move or add elements when you detect that your app is running on a larger screen. With adaptive code, you write your base code to run on the lowest OS version, and you can add hand-selected features when you detect that your app is running on a higher version where the new feature is available.

For important background info about ApiInformation, API contracts, and configuring Visual Studio, see Version adaptive apps.

Runtime API checks

You use the Windows.Foundation.Metadata.ApiInformation class in a condition in your code to test for the presence of the API you want to call. This condition is evaluated wherever your app runs, but it evaluates to true only on devices where the API is present and therefore available to call. This lets you write version adaptive code in order to create apps that use APIs that are available only on certain OS versions.

Numerous runtime API checks can affect the performance of your app. We show the checks inline in these examples. In production code, you should perform the check once and cache the result, then used the cached result throughout your app.

Unsupported scenarios

In most cases, you can keep your app's Minimum Version set to SDK version 10240 and use runtime checks to enable any new APIs when your app runs on later a version. However, there are some cases where you must increase your app's Minimum Version in order to use new features.

You must increase your app's Minimum Version if you use:

a new API that requires a capability that isn't available in an earlier version. You must increase the minimum supported version to one that includes that capability. For more info, see App capability declarations.

any new resource keys added to generic.xaml and not available in a previous version. The version of generic.xaml used at runtime is determined by the OS version the device is running on. You can't use runtime API checks to determine the presence of XAML resources. So, you must only use resource keys that are available in the minimum version that your app supports or a XAMLParseException will cause your app to crash at runtime.

Adaptive code options

There are two ways to create adaptive code. In most cases, you write your app markup to run on the Minimum version, then use your app code to tap into newer OS features when present. However, if you need to update a property in a visual state, and there is only a property or enumeration value change between OS versions, you can create an extensible state trigger that’s activated based on the presence of an API.

Use when there is only a property or enum change between OS versions that doesn’t require logic changes, and is connected to a visual state.

Benefits:

Lets you create specific visual states that are triggered based on the presence of an API.

Some designer support available.

Drawbacks:

Use of custom triggers is restricted to visual states, which doesn’t lend itself to complicated adaptive layouts.

Must use Setters to specify value changes, so only simple changes are possible.

Custom state triggers are fairly verbose to set up and use.

Adaptive code examples

In this section, we show several examples of adaptive code that use APIs that are new in Windows 10, version 1607 (Windows Insider Preview).

Example 1: New enum value

Windows 10, version 1607 adds a new value to the InputScopeNameValue enumeration: ChatWithoutEmoji. This new input scope has the same input behavior as the Chat input scope (spellchecking, auto-complete, auto-capitalization), but it maps to a touch keyboard without an emoji button. This is useful if you create your own emoji picker and want to disable the built-in emoji button in the touch keyboard.

This example shows how to check if the ChatWithoutEmoji enum value is present and sets the InputScope property of a TextBox if it is. If it’s not present on the system the app is run on, the InputScope is set to Chat instead. The code shown could be placed in a Page consructor or Page.Loaded event handler.

Tip

When you check an API, use static strings instead of relying on .NET language features, otherwise your app might try to access a type that isn’t defined and crash at runtime.

In the previous example, the TextBox is created and all properties are set in code. However, if you have existing XAML, and just need to change the InputScope property on systems where the new value is supported, you can do that without changing your XAML, as shown here. You set the default value to Chat in XAML, but you override it in code if the ChatWithoutEmoji value is present.

private void messageBox_Loaded(object sender, RoutedEventArgs e)
{
if (ApiInformation.IsEnumNamedValuePresent("Windows.UI.Xaml.Input.InputScopeNameValue", "ChatWithoutEmoji"))
{
// Check that the ChatWithEmoji value is present.
// (It's present starting with Windows 10, version 1607,
// the Target version for the app. This code is skipped on earlier versions.)
InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.ChatWithoutEmoji;
// Set InputScope on messaging TextBox.
scope.Names.Add(scopeName);
messageBox.InputScope = scope;
}
// For this example, set the TextBox text to show the selected InputScope.
// This is outside of the API check, so it will happen on all OS versions.
messageBox.Text = messageBox.InputScope.Names[0].NameValue.ToString();
}

Now that we have a concrete example, let’s see how the Target and Minimum version settings apply to it.

In these examples, you can use the Chat enum value in XAML, or in code without a check, because it’s present in the minimum supported OS version.

If you use the ChatWithoutEmoji value in XAML, or in code without a check, it will compile without error because it's present in the Target OS version. It will also run without error on a system with the Target OS version. However, when the app runs on a system with an OS using the Minimum version, it will crash at runtime because the ChatWithoutEmoji enum value is not present. Therefore, you must use this value only in code, and wrap it in a runtime API check so it’s called only if it’s supported on the current system.

Example 2: New control

A new version of Windows typically brings new controls to the UWP API surface that bring new functionality to the platform. To leverage the presence of a new control, use the ApiInformation.IsTypePresent method.

Windows 10, version 1607 introduces a new media control called MediaPlayerElement. This control builds on the MediaPlayer class, so it brings features like the ability to easily tie into background audio, and it makes use of architectural improvements in the media stack.

However, if the app runs on a device that’s running a version of Windows 10 older than version 1607, you must use the MediaElement control instead of the new MediaPlayerElement control. You can use the ApiInformation.IsTypePresent method to check for the presence of the MediaPlayerElement control at runtime, and load whichever control is suitable for the system where the app is running.

This example shows how to create an app that uses either the new MediaPlayerElement or the old MediaElement depending on whether MediaPlayerElement type is present.
In this code, you use the UserControl class to componentize the controls and their related UI and code so that you can switch them in and out based on the OS version. As an alternative, you can use a custom control, which provides more functionality and custom behavior than what’s needed for this simple example.

MediaPlayerUserControl

The MediaPlayerUserControl encapsulates a MediaPlayerElement and several buttons that are used to skip through the media frame by frame. The UserControl lets you treat these controls as a single entity and makes it easier to switch with a MediaElement on older systems. This user control should be used only on systems where MediaPlayerElement is present, so you don’t use ApiInformation checks in the code inside this user control.

Note

To keep this example simple and focused, the frame step buttons are placed outside of the media player. For a better user experiance, you should customize the MediaTransportControls to include your custom buttons. See Custom transport controls for more info.

Remember that this check only sets the mediaControl object to either MediaPlayerUserControl or MediaElementUserControl. You need to perform these conditional checks anywhere else in your code that you need to determine whether to use MediaPlayerElement or MediaElement APIs. You should perform the check once and cache the result, then used the cached result throughout your app.

State trigger examples

Extensible state triggers let you use markup and code together to trigger visual state changes based on a condition that you check in code; in this case, the presence of a specific API. We don’t recommend state triggers for common adaptive code scenarios because of the overhead involved, and the restriction to only visual states.

You should use state triggers for adaptive code only when you have small UI changes between different OS versions that won’t impact the remaining UI, such as a property or enum value change on a control.

Example 1: New property

The first step in setting up an extensible state trigger is subclassing the StateTriggerBase class to create a custom trigger that will be active based on the presence of an API. This example shows a trigger that activates if the property presence matches the _isPresent variable set in XAML.

The next step is setting up the visual state trigger in XAML so that two different visual states result based on the presence of the API.

Windows 10, version 1607 introduces a new property on the FrameworkElement class called AllowFocusOnInteraction that determines whether a control takes focus when a user interacts with it. This is useful if you want to keep focus on a text box for data entry (and keep the touch keyboard showing) while the user clicks a button.

The trigger in this example checks if the property is present. If the property is present it sets the AllowFocusOnInteraction property on a Button to false; if the property isn’t present, the Button retains its original state. The TextBox is included to make it easier to see the effect of this property when you run the code.

Example 2: New enum value

This example shows how to set different enumeration values based on whether a value is present. It uses a custom state trigger to achieve the same result as the previous chat example. In this example, you use the new ChatWithoutEmoji input scope if the device is running Windows 10, version 1607, otherwise the Chat input scope is used. The visual states that use this trigger are set up in an if-else style where the input scope is chosen based on the presence of the new enum value.