在Windows Universal App中检测当前设备

我正在尝试发布VS 2013 Update 2并构建示例通用应用程序。

我创建了一个用户控件,并在两个MainPages上添加了GridViews(在Windows Phone和Windows 8上)。

当应用程序在Windows Phone上运行时,我想通过代码更改一些内容。

有没有办法做这样的事情:

if( == "WindowsPhone") { } else { } 

通常,在构建应用程序时,您可以使用预处理程序指令。 在为windows phone构建app时,VS默认定义WINDOWS_PHONE_APP (查看Project Properties – > Build – > Conditional compilation symbols)。 因此,您可以在代码中的任何位置发出以下声明:

 #if WINDOWS_PHONE_APP // do when this is compiled as Windows Phone App #else // not for windows phoen #endif 

您可以在MSDN上获得更多信息。

我建议使用这种方法,因此在大多数情况下,您确切知道何时使用电话(ARM)或其他平台的特定代码。 当然,如果需要,可以为特定的构建配置/平台定义更多符号。

备注:从W10开始,您需要在运行时检查平台,然后可以使用ApiInformation类并检查api中是否存在特定类型。 例如这样:

 if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1)) // do code for mobile else // do code for other 

这在Universal Windows(Windows 10)项目中对我有用

 public static Platform DetectPlatform() { bool isHardwareButtonsAPIPresent = ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"); if (isHardwareButtonsAPIPresent) { return Platform.WindowsPhone; } else { return Platform.Windows; } } 

如果您想要一种确定当前设备的代码内方法,可以尝试这样做:

 public Windows.Foundation.Metadata.Platform DetectPlatform() { try { //Calls an unsupported API. Windows.Networking.BackgroundTransfer.BackgroundDownloader.RequestUncontrainedDownloadsAsync(null); } catch (NotImplementedException) { //The API isn't supported on Windows Phone. Thus, the current platform is Windows Phone. return Windows.Foundation.Metadata.Platform.WindowsPhone; } catch(Exception) { //Otherwise, this is Windows (desktop/RT). return Windows.Foundation.Metadata.Platform.Windows; } } 

资料来源: https : //gist.github.com/Amrykid/2fd65ae1815a928fe753

或者你可以这样做

将此添加到

App.Xaml.Cs

 public static bool IsMobile { get { var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues; return (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile"); } } 

来自GitHub

 public static class DeviceTypeHelper { public static DeviceFormFactorType GetDeviceFormFactorType() { switch (AnalyticsInfo.VersionInfo.DeviceFamily) { case "Windows.Mobile": return DeviceFormFactorType.Phone; case "Windows.Desktop": return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse ? DeviceFormFactorType.Desktop : DeviceFormFactorType.Tablet; case "Windows.Universal": return DeviceFormFactorType.IoT; case "Windows.Team": return DeviceFormFactorType.SurfaceHub; default: return DeviceFormFactorType.Other; } } } public enum DeviceFormFactorType { Phone, Desktop, Tablet, IoT, SurfaceHub, Other } 

https://gist.githubusercontent.com/wagonli/40d8a31bd0d6f0dd7a5d/raw/f6175de5fcad40cc257edc3748c0e349495d17f6/DeviceTypeHelper.cs

这是一种解决方法

  //PC customization if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView")) { } //Mobile customization if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { }