2

I am trying to get the current UI-AccentColor on the UWP platform using the following code:

var uiSettings = new UISettings();
var accentColor = uiSettings.GetColorValue(UIColorType.Accent);

This code works for v10586 and v14939 but fails for v10240 with the following exception:

Unable to cast object of 
type 'Windows.UI.ViewManagement.UISettings' to 
type 'Windows.UI.ViewManagement.IUISettings3'.

Question: Why is this code not working with v10240 although the method is defined in the used ApiContract [Assembly Windows.Foundation.UniversalApiContract, Version=1.0.0.0] and also all AccentColor-EnumValues are also defined in the ApiContract v1? And what is the best practice to avoid such errors although the documentation does not hint such exceptions?

The documentation specifies the availability of the used method for v10240: UISettings::GetColorValue and the used enums: UIColorType

I already found the StackOverflow Get Variations of Accent color in UWP but this does not solve my question.

A showcase project is given at: https://github.com/janjaali/UwpGetAccentColorVs10240

Community
  • 1
  • 1
Ghashange
  • 1,027
  • 1
  • 10
  • 20

1 Answers1

2

This looks like a bug in the contract listing, which then flowed into the docs.

GetColorValue is in IUISettings3 (hence the casting error mentioning it) which was new for the November update (build 10586). It should be UniversalApiContract version 2.0

You should be able to check if the API is available with the ApiInformation class. This will create a brush with the Accent colour, or fall back to an app-specific default if GetColorValue doesn't exist:

Brush accentBrush = (Brush) App.Current.Resources["CustomAppAccentBrush"];
if (Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.UI.ViewManagement.UISettings","GetColorValue"))
{
    var UISettings = new Windows.UI.ViewManagement.UISettings();
    var accentColor = UISettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Accent);
    accentBrush = new SolidColorBrush(accentColor);
}
Rob Caplan - MSFT
  • 21,714
  • 3
  • 32
  • 54